Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js won't make cross-host requests?

I've been playing with Backbone in my Chrome console and running into a cross-domain problem that I can't figure out.

The host I'm connecting to presumably correctly implements CORS because a raw XHR request returns the expected JSON:

var http = new XMLHttpRequest();
http.open('GET', 'http://example.com:3000/entities/item/15.json', true);
http.onreadystatechange = function(evt) { console.log(evt); }
http.send();

(logs 3 XHR progress events on the console with the correct data in the response)

But when I do the following with Backbone the browser doesn't like it:

var Item = Backbone.Model.extend({});
var ItemsCollection = Backbone.Collection.extend({
  model: Item,
  url: 'http://example.com:3000/entities/item/'
});
var items = new ItemsCollection();
items.fetch();

(returns XMLHttpRequest cannot load http://example.com:3000/entities/item/. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.)

Is there anything I need to do to tell Backbone to work with CORS? This error seems to have come before the browser even made a request, so I don't think it's a server config error.

like image 268
magneticMonster Avatar asked Apr 16 '13 15:04

magneticMonster


1 Answers

I hope one of these helps (I didn't try yet):
1. Overriding Backbone.js sync to allow Cross Origin

(function() {
  var proxiedSync = Backbone.sync;
  Backbone.sync = function(method, model, options) {
    options || (options = {});
    if (!options.crossDomain) {
      options.crossDomain = true;
    }
    if (!options.xhrFields) {
      options.xhrFields = {withCredentials:true};
    }
    return proxiedSync(method, model, options);
  };
})();

2. Cross domain CORS support for backbone.js

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    options.crossDomain ={
        crossDomain: true
    };
    options.xhrFields = {
        withCredentials: true
    };
});
like image 113
Ikrom Avatar answered Sep 21 '22 00:09

Ikrom