Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-Max-Age: 1728000

I am able to make a GET or POST request from hackst.com and it works fine. Link: http://hackst.com/#w3SbV

From my backbone app hosted on another domain, GET requests work fine. But when I try to create and save a new model (i.e. make a POST request), it fails with the following error:

Failed to load resource: the server responded with a status of 501 (Not Implemented) http://projectwhatup.us:5000/api/posts
XMLHttpRequest cannot load http://projectwhatup.us:5000/api/posts. Origin http://ayush.projectwhatup.us is not allowed by Access-Control-Allow-Origin.

My relevant backbone code:

var newPostData = {
    topic : "New Post",
    body : "new body",          
    user_id : 1,
};  

var newPostModel = new Post(newPostData);
this.model.create(newPostModel);

I even tried over-riding the create method and making a POST request manually like this:

create : function(data) {
    console.log('overriden create');

    $.ajax({
        "url" : this.url,
        "async" : true,
        "beforeSend" : function(obj){
            console.log(obj);
        },
        "contentType" : 'application/json',
        //"crossDomain" : true,  // uncommenting this doesnt help either
        "headers" : {

        },
        "dataType" : 'json',
        "type" : 'POST',
        "data" : JSON.stringify(data),
        "error" : function(err){
            console.log('new post creation failed');
            console.log(err);
        },
        "success" : function(resp){
            console.log('new post created');
            console.log(resp);
        }
    });
}

Same error.

I tried a stand-alone GET request on JSFiddle as well (http://jsfiddle.net/X9cqh/5/), but that fails even though my backbone app can make the GET request fine.

I'm completely clueless at this point. Any hints, pointers, solutions?

like image 672
xbonez Avatar asked Nov 20 '12 00:11

xbonez


People also ask

How do I fix XHR error?

How do I fix the XHR error? Technically, this is not error, it is normal response. The message tells you that you just tried to enter a secure room without the key, your error is that you don't have the key/authorization to enter that room. The only solution is to get the key/credentials and include on the request.

Why is CORS important?

The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.

When to use CORS?

CORS is a way to whitelist requests to your web server from certain locations, by specifying response headers like 'Access-Control-Allow-Origin'. It's an important protocol for making cross-domain requests possible, in cases where there's a legitimate need to do so.


2 Answers

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/).

like image 63
monsur Avatar answered Sep 29 '22 09:09

monsur


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.

like image 43
teddybeard Avatar answered Sep 29 '22 11:09

teddybeard