Unable to make https XMLHttpRequest requests - getting this back:
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:8443' is therefore not allowed access.
If I replace the url with www.google.com, it's fine, but https://www.google.com does the same thing.
It works when I use Postman/JaSON Chrome extensions, so I tried open -a Google\ Chrome --args --disable-web-security, but that didn't work either.
let request = new XMLHttpRequest();
request.open("POST", "https://outlook.office365.com/EWS/Exchange.asmx", true);
request.setRequestHeader("Authorization", "Bearer " + asyncResult.value);
request.setRequestHeader("Content-type", "text/xml; charset=utf-8");
request.setRequestHeader('Access-Control-Allow-Origin', '*');
request.setRequestHeader("Access-Control-Allow-Headers", "Content-type, Origin");
request.setRequestHeader("Access-Control-Allow-Methods", "POST");
request.onload = function() {
};
request.onerror = function() {
debugger;
}
request.send(requestBody);
The "Access-Control-Allow-Origin" header is set server-side for security reasons.
If you had access to the server you could just do:
header("Access-Control-Allow-Origin: *");
This, however, is not safe for obvious reasons. You should always allow as minimum external access as possible.
Recently I had the same issue. What I did was just use my own server, make the request from there to the api, and just have the script make the request to my server instead (from which you can set the access control header). So basically, instead of making the request to the third party client-side (from javascript), make it server-side and then get that data from your server via javascript.
Related
I'm trying to get informations from a SystemLinkServlet.
So I tried to execute this JavaScript code from a Nintex Forms (Sharepoint) :
var http = new XMLHttpRequest();
var url = 'www.exampleservlet.com';
var params = "anyxml"
http.open('POST', url, true)
http.setRequestHeader('Content-type', 'application/xml');
http.setRequestHeader('Access-Control-Allow-Origin', '*');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
};
http.send(params);
But I still got this error in my console :
Access to XMLHttpRequest at 'www.exampleservlet.com' from origin 'www.exampleorigin.com' 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.
It seems that the header is ignored or maybe I can't set multiple request headers?
It works on Postman.
Update
So It worked with an extension but apparently, I can't set headers with JavaScript code in my Nintex Forms.
I'm trying to find to pass those headers without using an extension.
If you are using PHP, try adding the following code at the beginning of the php file:
If you are using localhost, try this:
header("Access-Control-Allow-Origin: *");
If you are using external domains such as server, try this:
header("Access-Control-Allow-Origin: http://www.webiste.com");
Also you I suggest you to use this extension:
https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino?hl=en
Postman or other similar tools provide you development environments. In this way, you can ignore and pass CORS rule while sending request and getting response by changing tool settings. But if you sending request via browser(chrome, firefox etc.), browsers always add some preflight controls.
For example, browser send options message to get server side rule before your http request. So that invalid or wrong requests are blocked by browser before processing your http request.
In your case, server side must include your domain information. You can not change this communication rule from client side by adding just "Access-Control-Allow-Origin: *" or "Access-Control-Allow-Origin: http://www.webiste.com" statements.
I am using the Pons dictionary API documented here: https://en.pons.com/assets/docs/api_dict.pdf
It works when I use a get request in my mac terminal, but not when using XMLHttpRequest in my javascript file (shown below) when testing it in my browser. It always gives me a 404 error and then states
"Access to XMLHttpRequest at 'https://api.pons.com/v1/dictionary?q=casa&l=dees' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
Any ideas?
I have tried making a request that does not require my X-Secret (credentials) and it works, but as soon as I set the X-Secret header it throws a 404 error. I need to set this heading for most request types.
Here is my code. I have censored my credentials in the X-Secret header.
var request = new XMLHttpRequest()
let url = new URL('https://api.pons.com/v1/dictionary');
url.searchParams.set('q', 'casa');
url.searchParams.set('l', 'dees');
request.open('GET', url);
//request.withCredentials = true;
request.setRequestHeader("X-Secret", "***");
request.setRequestHeader("Access-Control-Allow-Origin", "*");
request.setRequestHeader("Access-Control-Allow-Credentials", "true");
request.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
request.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
request.send()
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
console.log(data)
} else {
console.log('error')
}
}
CORS is "cross-origin resource sharing"; specifically, it's used to refer to policies that block requests between different domains. In this case, XHR is sending a "preflight request" -- that is, a request with verb OPTIONS (rather than GET, POST, etc.) -- to make sure the server will accept a real request. It will do this whenever you use non-standard (and some standard but optional) headers. The preflight request is coming back as 404; the server doesn't support OPTIONS to that endpoint.
The way to get around CORS is to use a proxy. That is, have a backend script (in Node, PHP, whatever) on your domain that sends the request to the other API server and echoes its response. CORS only applies to AJAX requests, not backend ones, so this will get around the issue, and it is the accepted technique.
I am running a server on my localhost with an HTML5 application.
I would like to send an http-request to a second server "130.100.100.100:50000".
I have the following JavaScript code running on localhost where I am sending http requests to the second server.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {}
};
xmlhttp.open("GET", "http://130.100.100.100:50000/company.html/query?a0=" + a0, true);
xmlhttp.setRequestHeader( 'Access-Control-Allow-Origin', '*');
xmlhttp.send();
The second server is receiving my queries but I don't get any answer for my request. I think the problem is that the Same Origin Policy is violated. I tried to use the CORS standard to set
Access-Control-Allow-Origin: *
But the GET requests I am sending still doesn't contain "Access-Control-Allow-Origin" in the header. If I send the request manually with "Access-Control-Allow-Origin: *" everything is working proper. Do I have a mistake in my JavaScript code? I would like to avoid using jQuery.
You need to allow cross origin on server. Follow https://ma.ttias.be/set-access-control-allow-origin-cors-headers-apache-vhost-htaccess/
You need a page used as a proxy. This page will send a GET request to the target page and display the response. Make sure that relative paths at img, a, script and link are converted to full paths. If you do this, the CORS problem will be fixed.
I've been working with CORS and encountered the following issue.
Client complains about no 'Access-Control-Allow-Origin' header is present, while they are present, and client make the actual POST request and receives 200.
function initializeXMLHttpRequest(url) { //the code that initialize the xhr
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//set headers
for (var key in headers) {
if (headers.hasOwnProperty(key)) { //filter out inherited properties
xhr.setRequestHeader(key,headers[key]);
}
}
return xhr;
}
In Chrome
chrome console log
Chrome OPTIONS request
Chrome POST request
In Firefox
Firefox Console Log
Firefox OPTIONS request
Firefox POST request
In short: Access control headers (e.g. Access-Control-Allow-Origin) need to present in response for both OPTIONS and actual POST.
Work Flow:
Client make OPTIONS request with those HTTP access headers. (e.g. Origin, Access-Control-Request-Method, Access-Control-Request-Headers)
Server respond with those access control headers, allowing access. (e.g. Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Allow-Credentials, Access-Control-Allow-Methods, Access-Control-Allow-Headers)
Client makes POST request with data.
Server respond to POST. If Access-Control-Allow-Origin header is NOT present in the server response. Although the POST is successful and shows 200 status code in network tab, xhr.status is 0 and xhr.onerror will be triggered. And browser would show up the error message.
Header References:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Value null for Access-Control-Allow-Origin won't do, it has to be either the origin domain or * to allow any origin.
For more details, refer to MDN.
I'm struggling for quite some time already with issuing a simple GET request to a 3rd party REST Api. I've read a bit of tutorials and SO questions but I just can't get it to work. I am getting one of two errors
Response for preflight is invalid (redirect)
or (if via https)
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:8433' is therefore not allowed access.
About 2nd message: Is it just a problem with the server not supporting CORS?
My code:
var xmlHttp = new XMLHttpRequest();
var url = 'https://inspirehep.net/record/451647?of=recjson&ot=recid,number_of_citations,authors,title'; //http or https, tried both
/*
doing sth with response here like populate dropdown etc.
*/
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With, Cache-Control");
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", '*');
xmlHttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
xmlHttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
xmlHttp.send();
Whole app is running on node.js server (localhost) and the script above is included as separate file in .html view.
I can correctly get json response from web-browser, fiddler, postman etc. for this API. I also tried different APIs (e.g. Openweather API) thinking that it's the problem with server configuration, but the result was the same.
I would be thankful for any help - maybe i'm just misunderstanding something about CORS.
you cannot set headers from the browser, if the target url runs on your server or a server that you manage and that server runs nodejs you can use cors https://www.npmjs.com/package/cors, however, if this is a third party url and it doesn't not allow CORS, then you should make the request from the your back-end through configuring a proxy from your server to third party server, that should resolve your problem.
The answer on CORS with nodejs is most likely right, but I want to suggest that you run a test to make sure your code works fine as well.
Try with Chrome and download an extension to allow CORS. This way you will test the functionality first before trying the right solution.
Late to the party...
http://cors-anywhere.herokuapp.com/ is great, but you don't need it if you are using XMLHttpRequest() and a GET method. Simply exclude your header requests...
var xhr = new XMLHttpRequest();
xhr.open( "GET", YOURURL );
//OMIT THESE...
//xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
//xhr.withCredentials = true;
//xhr.setRequestHeader( 'Content-Type', _contenttype );
//xhr.setRequestHeader( 'CrossDomain', 'true' );
//....
xhr.addEventListener( 'load', function () {
xhr.responseJSON = JSON.parse( xhr.responseText );
alert( xhr.responseJSON);
});
xhr.onerror = function(e) {
alert("Ajax request error");
};
xhr.send( JSON.stringify({}) );