Skip to content Skip to sidebar Skip to footer

Cross Domain Xhr Failing

I have an API hosted on one domain that has CORS enabled with the following headers: Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-

Solution 1:

The server should also reply to the preflight with the following header:

Access-Control-Allow-Headers: Content-Type

This is necessary because the content type is application/json, which is outside the acceptable values defined in the CORS spec (http://www.w3.org/TR/cors/).

Solution 2:

Your sever setup works. JSFiddle apparently does not make the ajax requests, but you can quickly test that it works by entering these four lines into Chrome console or Safari developer console:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://projectwhatup.us:5000/api/posts', false);
xhr.send();
xhr.responseText;

enter image description here

If you try this with a domain that does not allow CORS, it will error out.

Solution 3:

The reason that adding a 'Content-Type' header makes your CORS request fail is because your server is set up wrongly.

If the client wishes to specify particular headers or use an unusual http method verb (e.g. PUT), then the browser will first do a 'preflight' OPTIONS call to ensure that it is allowed to set those headers. Your server needs to respond to this OPTIONS call with the appropriate headers. You'll see that options call in the network tab of the Chrome developer tools or firebug if you want to confirm that this is what the problem is.

You may be interested in my more detailed answer here.

Post a Comment for "Cross Domain Xhr Failing"