Isomorphic fetch gives CORS error - javascript

I am trying to covert my jQuery ajax call to use isomorphic fetch instead
My jQuery ajax call looks like this:
$.ajax({
url: 'myURL',
dataType: "script",
cache: true,
success() {
notify();
}
});
and my isomorphic fetch looks like this:
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/javascript');
fetch('myURL', {
headers: myHeaders,
mode: 'cors',
cache: 'default'
}).then(function(){
notify();
}).catch(function(error) {
console.log('request failed', error)
})
In the isomorphic-fetch version I am getting a CORS error in the browser:
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8080' is therefore not allowed access. The response had HTTP status code 501. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
However, the ajax call works fine.
What am I doing wrong?

Related

Request fails in browser, but returns 200 in fiddler with correct results, blocked by CORS policy

I am trying to set up an AWS lambda function, however when I call the endpoint, I am getting this error message back in the console.
Access to fetch at 'https://*.execute-api.eu-west-1.amazonaws.com/default/' 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.
I have set the CORS policy on the AWS Gateway
Here is my request code... I am just trying to print out the body of the response for testing purposes.
const response = await fetch(
'https://**********.execute-api.eu-west-1.amazonaws.com/default/**************',
{
method: 'POST',
body: "{'test': 'test'}",
headers: {
'X-Api-Key': '*****************************',
},
}
);
const text: any = await response.text();
console.log(text);
Weirdly when I look in fiddler, it is sending the OPTIONS and also returning a correct response, which is currently just printing out the different headers passed to the function.
If you've lambda proxy integration enabled you'll have to add headers from lambda.
From AWS documentation CORS section
For a Lambda proxy integration or HTTP proxy integration, you can still set up the required OPTIONS response headers in API Gateway. However, your backend is responsible for returning the Access-Control-Allow-Origin and Access-Control-Allow-Headers headers, because a proxy integration doesn't return an integration response.
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "https://www.example.com",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
you can read more here

google invisible reCaptcha server side validation is failing

i have integrated the invisible reCaptcha in my application and the client side response is coming as part of solving the image challenge. i am then calling a angular function to validate user response on server side using below code. where onloginSubmit(token) is the success call back.
<button id="btnLogin" ng-disabled="loginForm.$invalid"
class="g-recaptcha primarybtn margin-left-zero form-control-input"
data-sitekey="{{public_key}}"
data-callback='onloginSubmit'>{{'label_login' |
translate}}</button>
<script>
function onloginSubmit(token) {
angular.element(document.getElementById('loginForm')).scope().verifyReCaptcha(token);
};
</script>
in angular i am calling the verifyReCaptcha as below.
$scope.public_key = "------ My Site Key -------";
$scope.private_key = "------ My Secret Key -------";
$scope.verifyReCaptchaURL = "https://www.google.com/recaptcha/api/siteverify";
$scope.verifyReCaptcha = function(reCaptchaToken){
var captchaData = {
secret : $scope.private_key,
response : reCaptchaToken
}
$http({
headers: {
'Accept': 'application/json,text/plain',
'Content-Type': 'application/json;application/x-www-form-urlencoded;charset=utf-8;',
},
url: $scope.verifyReCaptchaURL,
method: 'POST',
data: captchaData
}).success(function (data) {
console.log("success");
$scope.login();
}).error(function (data) {
console.log("error");
$window.location.reload(true);
});
};
when i hit the api service https://www.google.com/recaptcha/api/siteverify . i get the below error.
Failed to load https://www.google.com/recaptcha/api/siteverify: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405.
i couldnt find more documentation for the issue.
what is it that i am doing wrong and also if there is any error the recaptcha does not come up and the login button which i am using fails to respond.
n the request i am mentioning the Method as Post, the method is over ridden as Options and the request payload which i am sending is not present. this is what i got in the networks tab
Request URL:https://www.google.com/recaptcha/api/siteverify
Request Method:OPTIONS
Status Code:405
Remote Address:10.120.118.50:8080
Referrer Policy:no-referrer-when-downgrade
Most of the thing you did a great job. One thing is to require in your application is communicate to an external domain so you can include HTTP header content type is include a JSONP format.
$http({
headers: {
'Accept': 'application/json,text/plain',
'Content-Type': 'application/jsonp;application/x-www-form-urlencoded;charset=utf-8;',
},
url: $scope.verifyReCaptchaURL,
method: 'POST',
data: captchaData
}).success(function (data) {
console.log("success");
$scope.login();
}).error(function (data) {
console.log("error");
$window.location.reload(true);
});

Getting the HTML source of a page in NodeJS

I'm currently struggling to get the HTML source of a webpage in NodeJS due to cors restrictions. Using JQuery I'm making a GET request to a page expecting an HTML response. This however throws the error XMLHttpRequest cannot load https://www.reddit.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. Is there a way to bypass CORS using NodeJS? (like via proxy)
$.ajax({
url: 'https://www.reddit.com/',
headers: {
'Content-Type': 'text/html',
"Access-Control-Allow-Origin": '*'
},
type: "GET",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
I'm also using webpack dev server with the following headers
headers: {
"Access-Control-Allow-Origin": '*',
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
}
Do not use jquery in nodejs, you can use this libs to archieve what you need:
isomorphic-fetch
request
Hope it helps

Cannot access Wikidata API

I'm trying to use the Wikidata API, but all I'm getting is:
Fetch API cannot load https://www.wikidata.org/w/api.php?action=wbsearchentities&search=Ingmar%20Bergman&language=en&limit=20&format=json&origin=http%3A%2F%2Fwww.dev.example.com%3A3000. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.dev.example.com:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is the code:
const headers = new Headers();
const origin = "http://www.dev.example.com:3000";
headers.append("Origin", origin);
headers.append("Content-Type", "application/json; charset=UTF-8");
const url = "https://www.wikidata.org/w/api.php";
const query = {
action: "wbsearchentities",
search: "Ingmar Bergman",
language: "en",
limit: 20,
format: "json",
origin
};
const myInit = new Request(url + "?" + qs.stringify(query), {
method: "GET",
mode: "cors-with-forced-preflight",
headers
});
fetch(myInit)
.then(function(res) {
console.log(res);
})
.catch(function(err){
console.log(err);
});
I have tried JSONP as well, no success. Running the link in the browser (just without the origin parameter) gives a proper response.
So why do you add the "origin" parameter at all? Just leave it off, or add "&callback=some_function" to get JSONP.
add origin=* to the querystring, e.g.
https://www.wikidata.org/w/api.php?action=wbsearchentities&language=es&type=item&format=json&origin=*&search=Agav

Cannot authenticate into BigCommerce API because of CORS

I want to make API calls into the BigCommerce API (https://developer.bigcommerce.com/api) using the Basic Authentication.
My AJAX call looks like following:
$.ajax({
type: 'GET',
url: 'https://store-zkk8z5i.mybigcommerce.com/api/v2/products',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + MY_TOKEN,
'Accept': 'application/json'
},
success: function (event) {
debugger
},
error: function (error) {
debugger
}
});
But I keep getting the following error:
XMLHttpRequest cannot load
https://store-zkk8z5i.mybigcommerce.com/api/v2/products. Response to
preflight request doesn't pass access control check: A wildcard '*'
cannot be used in the 'Access-Control-Allow-Origin' header when the
credentials flag is true. Origin
'http://store-zkk8z5i.mybigcommerce.com' is therefore not allowed
access. The credentials mode of an XMLHttpRequest is controlled by the
withCredentials attribute.
I'm pretty sure that my credentials are okay because I get successful responses when I make my requests using cURL.
Any ideas?
I'm pretty sure that my credentials are okay
That's rather beside the point. Look at the error message:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
Since you are sending credentials, you can't use a wildcard for Access-Control-Allow-Origin.
You have to say Access-Control-Allow-Origin: http://store-zkk8z5i.mybigcommerce.com and not Access-Control-Allow-Origin: *.

Categories

Resources