I want to do a cross-domain GET ajax request using jQuery v1.8.3.
Here is my setup:
-
I have a server on
domain1.devwhich issues these CORS headers for each requests:Access-Control-Allow-Origin: *Access-Control-Allow-Credentials: trueAccess-Control-Allow-Methods: *Access-Control-Allow-Headers: *
-
I have a web application on
domain2.devwhich load a javascript fromdomain1.devcalleddomain1.js.In this
domain1.jsfile, I issue this AJAX request:jQuery.ajax('http://domain1.dev/path', { headers: {'Accept': 'application/json'}, xhrFields: { withCredentials: true }, statusCode: { 200: function(data, textStatus, jqXHR) { // some logic }, 401: function(data, textStatus, jqXHR) { // some other logic } } }) -
I load the page from
domain2.dev. The AJAX request is issued (without preflight) and is successfull (status code 200) BUT firebug still displays it in red (chrome says “cancelled”) and I don’t understand why.
Any idea?
EDIT:
Response headers sent by the domain1.dev:
Access-Control-Allow-Cred... true
Access-Control-Allow-Head... Accept, Accept-Encoding, Accept-Language, Connection, Cookie, Host, Origin, Referer, User-Agent
Access-Control-Allow-Meth... GET
Access-Control-Allow-Orig... *
Cache-Control private
Connection keep-alive
Content-Type application/json
Date Thu, 22 Nov 2012 22:24:44 GMT
Server nginx/1.2.3
Transfer-Encoding chunked
X-Powered-By PHP/5.4.6
x-debug-token 50aea62c91ee6
while the request headers were:
Accept application/json
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Cookie obfuscated=uk40mmmqbffues5cpn6omj6mf0; __utma=126865951.1486960365.1353615466.1353615466.1353619027.2; __utmz=126865951.1353615466.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmc=126865951
Host domain1.dev:8080
Origin http://domain2.dev:8080
Referer http://domain2.dev:8080/app_dev.php
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/17.0 Firefox/17.0
At the backend, you must explicitly state which headers and methods you want to allow. The
Access-Control-Allow-MethodsandAccess-Control-Allow-Headersresponse headers do not support wildcards.If you want to allow any method / header, just look for the
Access-Control-Request-MethodsandAccess-Control-Request-Headersheaders in the (preflight) request, and return the literal value.And, you cannot use a wildcard for
Access-Control-Allow-OriginwhenwithCredentialsis true. Either use the same mechanism as described earlier to simulate the wildcard, or don’t usewithCredentials.