Cross Origin GET Request CORS Error with Data Power - javascript

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.

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

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

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)

Unable to retrieve data from http site to https using XMLHttpRequest()

I have a site hosted on https:// in which I want to pull data from the site which shows the properties of the shares. The URL which returns the data is:
http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
The code which I have developed to get the data is as follows:
function GetSharesUpdate(){
// makeing AJAX calls to the web service for getting the share update
var xhr = new XMLHttpRequest(); // Set up xhr request
xhr.open("GET", "http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191", true); // Open the request
xhr.responseType = ""; // Set the type of response expected
xhr.send();
// Asynchronously wait for the data to return
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
var tempoutput = xhr.responseXML;
alert(tempoutput);
}
}
// Report errors if they happen
xhr.addEventListener("error", function (e) {
console.error("Error: " + e + " Could not load url.");
}, false);
}
I am getting the error on the statement xhr.send(); which is as below:
Mixed Content: The page at 'https://[SiteUrl]' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint
'http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191'.
This request has been blocked; the content must be served over HTTPS.
If I change the URL to https i.e.
https://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
then xhr.send(); is executed without any error but I am getting xhr.responseXML null.
What should I make changes in my code to make it working?
The first problem is you are doing ajax request to non-https domain but your domain has SSL installed.
The second problem is Cross origin request CORS, you will have this problem even you solve first (ie. even you try ajax request from non-http domain).
Since you are requesting data from another website this is most likely to happen unless the requested server is configured to serve requests for you domain
To solve this you need to call the data from your server(proxy server) or have the requested server configured to allow requests from your domain.
See more - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

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

XMLHttpRequest and Web Workers Access-Control-Origin

I'm dealing with some Access-Control-Origin issues when using webworkers to make an XMLHttpRequest.
The issue is easily reproducible in this code, main.js:
var worker = new Worker('js/createSimplePage.js');
worker.onmessage = function () {
console.log('message recieved');
};
And js/createSimplePage.js:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "http://search.twitter.com/search.json?q=balling&rpp=20&callback=", true);
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
xmlhttp.send();
If I include createSimplePage.js in the header of index.html, it runs fine and prints the correct response from the twitter API. However, if I only load main.js and let it try to load createSimplePage.js as a web worker then I receive the error:
XMLHttpRequest cannot load http://search.twitter.com/search.json?q=balling&rpp=20&callback=.
Origin file:// is not allowed by Access-Control-Allow-Origin.
A similar error occurs when hosting the files on SimpleHTTPServer except the error is then
"Origin http://127.0.0.1:8000 is not allowed by Access-Countrol-Allow-Origin."
I don't understand why loading it as a web-worker would break it so it can't access the API.
I don't think webworkers have the same security level as the browser. Maybe you could ensure you scripts are returned with allow all origins header:
header("Access-Control-Allow-Origin: *");
and probably best to removed your custom header:
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
This site has more information:
http://enable-cors.org/

Categories