I am trying to create a cross origin GET request using jQuery.ajax(). My server is configured to accept such requests. Chrome will not allow me to send the headers:
Access-Control-Request-Method
Access-Control-Request-Headers
Refused to set unsafe header "Access-Control-Request-Method" <- error message
Here is my ajax request:
$.ajax({
type:"GET",
headers: {
'Access-Control-Request-Method' : 'GET',
'Access-Control-Request-Headers': 'X-Custom'
},
url: "http://localhost:3000",
success: function(msg) {
console.log(msg);
}
});
I was expecting these headers to cause the browser to create a pre-flight request (OPTIONS) to negotiate with the server. I know that I have accomplished this before. Can someone tell me what I am forgetting?
Thanks a lot!
A PREFLIGHT options request automatically takes place on a cross domain request IF the request is not a simple request. A simple request is typically a GET request. Thus if you make a cross domain GET request there will NOT be a preflight OPTIONS request.
However, if you make a cross domain POST request, the browser will, without you instructing it to do so, make a preflight OPTIONS request first. The purpose of this request is to see whether the server permits cross-domain POST requests from your client's domain / IP.
If your server has the correct "Access-Control" headers in the response, that say, yes this client is permitted to make a cross domain POST request, then the browser will proceed to make the POST request. If your server says NO (because the "Access-Control" headers on your server are wrong) then the browser will respect that and will NOT make the second POST request.
See https://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request for more info.
Also, you must make sure your server is set to handle incoming OPTIONS requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With