422 error 'unprocessable entity' when calling API from Chrome extension - javascript

I am building a Chrome extension that aims to send information (url, title etc.) from the current page the user is on to a REST API with a Rails backend. The API call works when I test it with Postman but when I send the data through my extension, I receive the 422 (Unprocessable Entity) error.
This file listens for the click in my extension:
function listenClick() {
const button = document.getElementById('send-data');
button.addEventListener('click', () => {
chrome.tabs.executeScript({
file: 'scripts/send-data.js'
});
})
}
listenClick();
This is the send-data.js file:
function fetchData() {
title = document.querySelector('title').innerText;
const url = window.location.href;
return {
title: title,
url: url
}
}
function sendData(data){
const url = 'http://localhost:3000/api/v1/bookmarks';
fetch(url, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-User-Email": "test#mail.com",
"X-User-Token": "asdfkljIOJDHalsdfkla"
},
body: JSON.stringify({
"title": `${data.title}`,
"url": `${data.url}`,
})
})
}
sendData(fetchData());
The error occurs on the line starting with 'X-User-Email'. I am using the 'simple_token_authentication' gem to authenticate users, which uses these headers.
Could someone help me to see what I'm missing?

Realized that the problem was with my ruby code and not with the js.file quoted above. Checking the rails logs helped me realize that.

Try changing the content type of the header. header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' }

Related

No response from API

I have created an API call in excel to get data from a Wix database.
The call:
Dim http As Object, JSON As Object
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://username.wixsite.com/mysite/_functions/Functionname", False
http.setRequestHeader "Authorization", "myauthkey"
http.Send
MsgBox (http.responseText)
The javascript http backend file on Wix:
import { ok, notFound, serverError } from 'wix-http-functions';
import wixData from 'wixdata';
export function get_Wixdata() {
let options = {
"headers": {
"content-type": "application/json"
}
};
return wixData.query("wix data collection name")
.find()
.then(results => {
if (results.items.length > 0) {
options.body ={
"items": results.items
}
return ok(options);
}
})
}
I tested the call (without authorisation) on JSON place holder and it worked fine.
Just trying to debug what's happening as I am getting "" as a response.
Even if I enter the wrong API key I still get "", even a wrong url it's still a "" response.
I take it I am clearly way off the mark with what I am trying to do..
Did you tried put both headers in your request, like the following:
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': '....'
});
The issue was with the VBA call, the header was not needed.
Dim https As Object, JSON As Object
Set https = CreateObject("MSXML2.XMLHTTP")
With CreateObject("Microsoft.XMLHTTP")
.Open "GET", "end point url", False
.send
response = .responseText
End With

cy.request doesn't allowing me to go to next UI test cases

Trying to integrate both UI & API test cases
Created two files:
API test --> DO Login and writing token & saving it to fixture file
Spec test -->Do REAL Login by using username and password and once test case pass then in next test first get the response by using cy.request using token which saved by step1. Based on response keys search the data in search bar
API Test File:
it("Login Request API",function(){
cy.request({
method:"POST",
url: POST URL,
headers:{
"content-type" : "application/json"
},
body : {
"email": USER NAME,
"password": PASSWORD
},
log: true
}).then((response) => {
// Parse JSON the body.
expect(response.status).to.equal(200)
let resbody = JSON.parse(JSON.stringify(response.body));
cy.writeFile("File Path to store response",resbody)
})
});
Cypress version: 3.8.3
Once above test is executed then it redirect to first test . Not going to further tests
For Cypress Version 3.8.3: You may need to check the path of the new file you are trying to create. it is by default within the 'fixture' folder.
cy.request({
method:"POST",
url: POST URL,
headers: {
"content-type" : "application/json"
},
body : {
"email": USER NAME,
"password": PASSWORD
},
log: true
}).then((response) => {
// Parse JSON the body.
expect(response.status).to.equal(200);
cy.writeFile("<path>/api.json", response.body); // <path> is with respect to cypress/fixture folder
});
From my test:

Need to modify the URL inside a onClick function while invoking fetch in reactJS

I am new to reactJS.
The below snippet is to invoke a URL on a click event.
But the URL fired is with the baseURI.
How can i truncate that or reset it ?
handleClick = (event) => {
console.log("Got the row " + event );
alert('The link was clicked.'+ event);
fetch("www.google.com")
.then(res => {
console.log("Got the result "+ res.json());
}
);
};
The URL fired is
Response:
{type: "basic", url: "http://localhost:3000/www.google.com", redirected: false,
status: 200, ok: true, …}
(...)
statusText: "OK"
type: "basic"
url: "http://localhost:3000/www.google.com"
I need to fire multiple calls within this handleClick event and then open a new tab if successful with the final URL along with the session key. The above code is just the beginning to check the calls work fine or not.
How should i truncate "http://localhost:3000" ??
Fetch API doesn't know that it's an external link. Add the protocol to your url, i.e. http:// or https://.
Fetching API from external link, you need to add complete URL like
http://google.com
or
https://google.com
just pass the fetch options:
fetch(URL, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin':'*'
}
})

Ionic v1 AngularJS $http POST request not working

I'm trying to send a POST request to a rest API, but I don't seem to able to do it correctly, I don't know if it's the syntax, or what it could be, I've tried many different ways but nothing seems to work. Here's is some pictures of the service being consumed by POSTMAN (everything works fine here).
The Headers
And the body with the response
But then when I try to consume the service via AngularJS, it keeps sending me erros messages, the localhost server even detects that there is a request, because I can see it on the Eclipse's console, but it doesn't run through the debugger with togglebreakpoints and it does with POSTMAN.
This is one of the many attempts to send a $http request
var json = { practiceId: 1 };
$http({
method: "POST",
url: "https://localhost/GetAppointmentTypes",
data: JSON.stringify(json),
headers: {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
}
})
.success(function(data) {
$ionicPopup.alert({
title: 'WORKING'
});
})
.error(function (errResponse, status) {
if(status == 403){
$ionicPopup.alert({
title: '403'
});
}
});
But then
And here is another attempt
var url = 'https://localhost/GetAppointmentTypes';
var parameter = JSON.stringify({practiceId:1});
var headers = {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
};
$http.post(url, parameter, headers).then(function(response){
$ionicPopup.alert({
title: 'WORKING'
});
}, function(response){
$ionicPopup.alert({
title: ' NOT WORKING '
});
});
And the response
Note: the $window.localStorage['token'] is working correctly. I have tried so many things I don't even know what I'm doing wrong now, might be a syntax error, but then ERROR 403 wouldn't be showing.
EDITED (ADDED)
And the Response Variable

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

Categories

Resources