Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS not working on Chrome

I've set up Cross-Origin Resource Sharing on a server (Jetty using the CrossOriginFilter) and it works perfectly on IE8 and Firefox. On Chrome, it just ... doesn't.

  $.ajax({ url : crossOriginURL,     type : "GET",     error : function(req, message) {         alert(message);     },     dataType :  "json" } ); 

The error function is invoked, with the helpful message "error". It seems to be making the request, but without any of the headers you'd expect. If the URL is from the same origin, it works fine.

like image 257
Michael Lorton Avatar asked Jun 28 '10 21:06

Michael Lorton


People also ask

How do I fix CORS problem in chrome?

i. Turn OFF the CORS plugin, reload the app, at this time you should still get the errors which are correct. ii. Turn it back ON, reload the app, if the APIs are successful, stop here, no need to proceed to iii.

How do I enable CORS in chrome?

Allow CORS: Access-Control-Allow-Origin. Easily add (Access-Control-Allow-Origin: *) rule to the response header. Allow CORS: Access-Control-Allow-Origin lets you easily perform cross-domain Ajax requests in web applications. Simply activate the add-on and perform the request.

Why CORS is not working?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.


1 Answers

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"} ); 
like image 90
cusspvz Avatar answered Oct 04 '22 16:10

cusspvz