CORS not working on Chrome
Solution 1:
I have solved my problem this way:
Add this to your PHP Code:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
Or add these headers to your response.
Problem: The browsers ask to the server for options before your main request, to check if the site has the option to allow comunication with different origin, and then if yes, they do your POST or GET request.
EDIT: Try this (without your hack) to see if you're receiving data...
$.ajax({ url : crossOriginURL,
type : "GET",
error : function(req, message) {
alert(message);
},
success : function(data) {
alert(data);
},
dataType : "text"} );
Solution 2:
what finally worked for me is xhr.setRequestHeader('Content-Type', 'text/plain');
EDIT: The server needs to add Access-Control-Allow-Headers: Content-Type
to avoid this problem.
I am coming back to my own question a decade later. I don’t know if this is a good thing or a terrible thing.
Solution 3:
It looks like the original poster may have resolved their issue, but for anyone having the same issue as commentor Elisabeth, I believe the problem may be that Chrome refuses to set a an Origin header for a CORS request if you are running the request from a local file. It won't even let you explicitly override the Origin header. This causes the server to see "Origin: null", which results in a 403 in most cases. Firefox apparently has no such constraint, as I've found after much hair-pulling.
If you absolutely need to use Chrome in this case, you can resolve your issue by running a webserver locally and always accessing your file via http: instead of via file:.