jQuery Ajax - 400 error and CORS problem with Allow-Origin: * - ajax

I don't know why I get CORS errors, even if everything seems well settled.
This is my Nodejs Express server configuration:
function setupCORS(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Accept');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
res.status(200).end();
} else {
next();
}
}
app.all('/*', setupCORS);
This is my client jQuery request:
var headers = {"Content-Type" : "application/json"}; // <----
jQuery.ajax( {
url : url,
type : 'POST',
data : data,
headers : headers,
dataType: 'json',
success : function(response) { }
});
.done(function()
{})
.fail(function(err)
{ console.error(err); })
.always(function()
{ });
It doesn't work, I always get CORS error
[Error] Origin ://mysite.com is not allowed by Access-Control-Allow-Origin. Status code: 400
[Error] XMLHttpRequest cannot load ://server_endpoint.com/api due to access control checks.
If I don't specify content-type, and just use
var headers = { };
everything works fine. Why?

Related

Cors : Can GET but not POST

I developing an application trough Ionic React.
The API is made with Laravel. I have the good data in the header of the response with 200 status.
Access-Control-Allow-Origin *
Access-Control-Allow-Credentials true
Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS
Client side :
static getStat(): Promise<any>{
return fetch(`http://192.168.1.250/bodt78/public/api/index`,{
method: 'GET',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then((response) => {
if(response.status === 200){
return true
}
else{
return false
}
})
.catch(error => this.handleError(error));
}
This one works perfectly ... but when I want to make a request for the login ( POST )
return fetch(`http://192.168.1.250/bodt78/public/api/auth/login`,{
method: 'POST',
headers: { 'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:8100',
},
body: JSON.stringify({
"email": email,
"password": password}),
}).then((res) => {
console.log(res);
if (res.status == 200) {
return res.json();
} else {
if (res.status == 401) {
return res.status;
} else {
return null;
}
}
});
Every time I try to fetch ... I have an error :(
[Error] Origin http://localhost:8100 is not allowed by Access-Control-Allow-Origin.
[Error] Fetch API cannot load http://192.168.1.250/bodt78/public/api/auth/login due to access control checks.
I edit the ionic.config.json with :
"proxies": [{
"path": "/bodt78/public/api",
"proxyUrl": "http://192.168.1.250"
}]
Do you have any idea ? I tried literally everything !
#sideshowbarker save your time and go to do something else rather than ban people just to improve the rank of your answer !
Thanks

Authorization failed on a fetch request to the Brawl Stars API

I'm trying to send a get request with fetch API to ask the brawl stars API server. I've created an API KEY associated with my IP address. I've tried everything, but I got a 403 response from the server.
Here is my code :
const url = 'https://api.brawlstars.com/v1/players/...';
const token = '...';
const headers = new Headers({
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
});
const options = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
};
fetch(url, options)
.then(response => response.json())
.then(console.log)
.catch(console.error);
In the console there is the message : No 'Access-Control-Allow-Origin' header is present on the requested resource because of cors policy.
When I test the request on Insomnia, it works well !
I had a problem with the Brawlstars API a little while back when I was making a Brawlstars command for my Discord bot. I was able to get the API to work however with the following code.
const playerurl = 'https://api.brawlstars.com/v1/players/';
const getJSON = async url => {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer <yourapitoken>',
},
});
if(!response.ok) {throw new Error(response.statusText);}
const data = await response.json();
return data;
}
catch(error) {
return error;
}
};
getJSON(playerurl).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
I hope this works for you!

Getting 502 response and 'has been blocked by CORS policy' running a simple fetch request to my lambda function

Building a serverless web app on AWS with the serverless framework, I get a CORS error with a 502 response code authenticating against an AWS Cognito user pool
GET https://URL.amazonaws.com/dev/asset/ID-1178 502
index.html:1 Access to fetch at 'https://URL.amazonaws.com/dev/asset/PO-TIENDA1178' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.js:109 Uncaught (in promise) TypeError: Failed to fetch
An almost identical request works for another function.
And here are both ajax requests sent from the frontend:
// working just fine
async function getAllAssets() {
const getAssetsUrl = _config.api.invokeUrl + "/assets"
const response = await fetch(getAssetsUrl, {
headers: {
Authorization: authToken
},
type: "GET",
dataType: 'json',
crossDomain: true
})
}
// not working, throwing the error described above
async function getOneAsset() {
const getAssetsUrl = _config.api.invokeUrl + "/asset/" + "ID-1178"
const response = await fetch(getAssetsUrl, {
headers: {
Authorization: authToken
},
type: "GET",
dataType: 'json',
crossDomain: true
})
}
I run both functions onDocReady in the same window.
Here are the definitions in serverless.yaml:
# WORKS 👌🏽
getAssets:
name: ${self:service}-${self:provider.stage}-get-assets
handler: handler.getAssets
role: InventoryLambdaRole
events:
- http:
path: /assets
method: get
cors: true
authorizer:
arn: arn:aws:cognito-idp:eu-west-1:HARDCODED:ARN
# doesn't work
getAsset:
name: ${self:service}-${self:provider.stage}-get-asset
handler: handler.getAsset
role: InventoryLambdaRole
events:
- http:
path: /asset/{assetId}
method: get
cors: true
authorizer:
arn: arn:aws:cognito-idp:eu-west-1:HARDCODED:ARN
And here goes my function implementations in the handler.js:
// get all assets works fine:
module.exports.getAssets = function(event, context, callback) {
const params = {
TableName : 'Assets',
Select: 'ALL_ATTRIBUTES',
}
const request = documentClient.scan(params, function(err, data) {
if (err) {
console.log("Error", err)
} else {
const itemCount = data.Count
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
itemCount: itemCount,
assets: data
}),
}
callback(null, response);
}
})
}
// get one asset doesn't work:
module.exports.getAsset = function(event, context, callback) {
const params = {
TableName : 'Assets',
Key: {
AssetId: event.pathParameters.assetId // also tried to just hardcode it like this: 'ID-1178'
}
}
const request = documentClient.get(params, function(err, data) {
if (err) {
console.log("Error", err)
} else {
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
asset: data
}),
}
callback(null, response);
}
})
Although it's a CORS error, as you can see the origin headers are provided, and I found that in combination with the 502 status it might be something before the CORS, e.g. a problem in the function or with authorization. However, I can't see any problems with them so far.
The serverless function itself works as well when invoke it locally:
npm run sls -- invoke local --function getAsset -p test.json
Do you have any ideas what could be the issue or how to debug it?
Your issue may be as simple as having dynamodb:GetItem. This is a different permission than what listing all (ie query or scan) would be

Jhipster Spring backend - Social login & React Native frontend

I have created Spring as backend and enabled social login for google authentication. /signin/google is the endpoint with a method POST and content type is application/x-www-form-urlencoded with scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email.
Postman client works perfectly fine if i invoke the above mentioned endpoint from postman client(Google chrome app) it gives me 200 status code and JSESSIONID and i am able to invoke the other secure api.
but for react native i am unable to execute it. Help would be highly appreciated. Mentioned below is the function that i am using to trigger google signin.
googleSignin = () => {
var data = 'scope=' + encodeURIComponent('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email');
axios({
url: baseUrl + 'signin/google',
method: 'POST',
data: data,
config: {
headers:
{
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': true
},
credentials: "same-origin"
},
withCredentials: true
})
.then(res => {
console.log('googleSignin res() ---> ', res.headers);
})
.catch(e => console.log(e));
};
It always gives me CORS error policy. mentioned below is the cors configuration on the backend.
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "Access-Control-Allow-Headers, Authorization, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
exposed-headers: "Authorization,Link,X-Total-Count"
allow-credentials: true
max-age: 1800
and screenshot is the error:
This is a cross-domain issue. After jQuery 1.5.0 and later, the cross-domain was blocked. As a result, the following error occurs when requested by ajax:
Try this code.
const options = baseUrl + 'signin/google'
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = [removed].protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.post(
options,
function (response) {
console.log(">>>> " + JSON.stringify(response));
});

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

I'm using axios to send http requests ( i used fetch also but it gives the same result ).
axios.post("http://localhost:3000/login",
{
answer: 42
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
In my go file I'm logging the response
func post(req *http.Request, res http.ResponseWriter) {
req.ParseForm()
fmt.Println(req.Form)
}
The log is as follows :
map[{"answer":42}:[]]
However i want it to be as follows :
map["answer":[42]]
(I get such when i use postman)
What is the issue with this.
Outgoing data for reference
UPDATE
I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.
Its just with axios and fetch which is not working
Here is the code :
request
The following code using nodejs request
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/login',
headers:
{
'cache-control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { answer: '42' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
jQuery ajax
The following is my jQuery code
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/login",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"answer": "42"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
However, I am still unable to get axios and fetch to work. If someone finds it please update the answer
You need something like this:
var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
'Content-Type': 'application/x-www-form-urlencoded'
});
You can set query string parameters using the params config option,
It will definitely works:
axios.post("http://localhost:3000/login", "", {
params: {answer: 42},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

Resources