CORS Policy when calling an REST API, JavaScript [duplicate] - javascript

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
I'm trying to call an API in JavaScript, if I write it in the URL bar, it works but if I use my code, it has CORS policy problem. I don't have any access to the server and I should find a way to solve in the client side.
This is my code:
var xhr = new XMLHttpRequest();
var url = 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-Key';
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader("APPID", "MY API Key");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Origin', '*');
//console.log(json);
xhr.send();
xhr.onload = function () {
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
alert(`Done, got ${xhr.response.length} bytes`);
}
};
xhr.onprogress = function (event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function () {
alert("Request failed");
};
</script>
and it has the error:
Access to XMLHttpRequest at 'https://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-key' from origin 'https://localhost:44399' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Anybody has Idea how to solve this error? where should I send my Origin or anything else as a header to get the correct response from the server?
I should handle it in the client side and also I have written the Origin * in the header but still not working.
Best Regards

have you tried to use the "allow-origin: *" Header on your server ?
It's maybe the cause of the problem (your server doesn't accept theses requests)

Related

I get a CORS-Error while doing a request for a API using XHR

We’re making a request for an API from one of our online-distributors.
However, we get a CORS-Error.
Access to XMLHttpRequest at 'https://api.cloud.im/marketplace/eu/products' from origin 'http://www.im-cmp.ch' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
We did the request in Postman and it worked. I tried to set the requestHeaders the exact same way they are set in Postman (including the hidden headers), however, there is an Error since the hidden headers can’t be set.
Refused to set unsafe header "Host"
Is this a client or a server problem? Am I maybe missing a requestHeader?
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.cloud.im/marketplace/eu/products");
xhr.setRequestHeader("X-Subscription-Key", "OUR PERSONAL SUBSCRIPTION KEY");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "OUR BEARER TOKEN");
// xhr.setRequestHeader("Host", "http://www.im-cmp.ch/");
xhr.setRequestHeader("accept", "*/*");
// xhr.setRequestHeader("Accept-Encoding", "gzip, deflate, br");
// xhr.setRequestHeader("Connection", "keep-alive");
xhr.send();
This is definitely a server problem.
The server has to send the Access-Control-Allow-Origin-header: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.
Also, the error states that this happened during a preflight-request, meaning there was a OPTIONS request made beforehand, which would also need the response-header(s) needed for CORS.
The request works in Postman, since CORS is a feature only really relevant in browsers, to protect users.
Edit:
Also it is important that the server allows the request-headers you are sending using the Access-Control-Allow-Headers-header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

Cross Origin GET Request CORS Error with Data Power

I am trying to connect to Denodo to pull back information via an API call, but I have to go through Data Power for security reasons. When bypassing Data Power, we are able to successfully retrieve the data from Denodo. I have been informed that everything is set up in Data Power correctly for the response headers and the configuration is set to allow our web application. Below is the code we use to make the call:
var xhr = new XMLHttpRequest();
xhr.open("GET", "target URL", true);
xhr.withCredentials = true;
xhr.setRequestHeader('Access-Control-Allow-Origin', 'source URL');
xhr.setRequestHeader('Access-Control-Allow-Credentials', 'true');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.response);
console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
We receive the following error in the console when executing the function:
Access to XMLHttpRequest at 'target URL' from origin 'source URL' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
We have tried a variety of different options to get this to work, but we still can't. I've searched the forums for similar issues, and the responses have been tried unsuccessfully.

GET XMLHttpRequest stops at readystate 4 and status 0

I've been trying to get article from NewsAPI.org but I got this error:
Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=us&category=general&apiKey=XXXXXXXXXXXXX' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And I noticed it stops at readystate 4 and status 0.
this is the code of the function I use:
function getNews()
{
var url = 'https://newsapi.org/v2/top-headlines?country='+country+'&category='+category+'&apiKey=XXXXXXXXXXXXX';
var req = new XMLHttpRequest();
req.open('GET' , url);
req.send();
req.onreadystatechange = function()
{
if(req.readyState == 4 && req.status == 200)
{
news = JSON.parse(req.response);
news = news.articles;
displayNews();
}
}
}
Note: I tried to add the 'Access-Control-Allow-Origin' header but it makes no change.
First of all, the xhr request is not stopping at req.readystate == 4 instead at res.send(). Also CORS is a standard web security service provided by the browser to prevent data leak from other origin.
For testing locally, you can bypass it by adding the header:
Access-Control-Allow-Origin: *

Why axios cause Access-Control-Allow-Origin error

I have pretty basic axios code:
axios.get(GEO_IP)
.then(res => res)
.catch(err => err);
Also, I set next axios defaults:
axios.defaults.headers["content-type"] = "application/json";
axios.defaults.headers.common.authorization = `Bearer ${token}`;
authorization token no needed for this public API. When I try to fire query using axios.get, I see next error in console:
Failed to load https://ipfind.co/me?auth=8964b0f3-4da1-46eb-bcb4-07a9614a6946: 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:3000' is therefore not allowed access.
When I rewrite axios using native XMLHttpRequest:
new Promise((resolve, reject) => {
const http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
// result
}
};
http.open("GET", GEO_IP, true);
http.send();
});`
Everything works fine, without any errors. Could someone clarify why axios query causes the error and how I can fix it?
The error message says:
Response to preflight request
This has nothing to do with axios. You are trying to send different requests. When you are using axios, you are setting up the request in such a way that a preflight is required.
axios.defaults.headers["content-type"] = "application/json";
axios.defaults.headers.common.authorization = `Bearer ${token}`;
Either of the above would trigger a preflight.
The XMLHttpRequest version (which doesn't set HTTP headers) doesn't require a preflight, so the server not supporting the preflight isn't a problem.
This means that while your server sends the right CORS headers for the GET request, it isn't for the OPTIONS request that is being sent by axios as part of the preflight request.
Some requests don't require a preflight request. But I'm guessing that axios always sends one.
See MDN for more details on this.

Cross-domain post to external site fails on wordpress

I'm trying to post data to an external website from a wordpress site using Javascript, however when i send the form i'm getting this:
XMLHttpRequest cannot load https://external_site.com/embed/documents.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://my_site.com' is therefore not allowed access.
The response had HTTP status code 404
I'm trying to this from a Wordpress site, this is the Javascript part that sends the data
jQuery('#send_doc').click(function(){
var url = jQuery('#document_url').val();
var name = jQuery('#name').val();
var request = new XMLHttpRequest();
request.open('POST', 'https://external_site.com/embed/documents');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Token my_token
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'document_url': url,
'name': name
};
request.send(JSON.stringify(body));
});
My question is, i understand that this is a Cross-domain problem, but my question is: Can i resolve the problem by my side or is this problem just on the externa site side?
Thank you very much for your answers

Categories