I’m working on a backbone.js project and I’m calling my github repo. I have the my Collections and Models bootloaded so they exist once my page is built, but when I call model.fetch() I get this message: (replace :username with a username)
XMLHttpRequest cannot load https://api.github.com/users/:username.
Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin.
I’ve read a few messages post1, post2, they mention modifying the backbone.sync function but I’m not entirely sure how. Here is my code so far (this is in my Backbone.Router):
userDetails: function(id) {
console.log('Loading: userDetails');
var User = Users.get(id);
User.fetch({dataType: "jsonp"});
console.log(User);
userView = new UserView({
model: User
});
userView.render();
},
Thanks!
CORS is enabled on the backend. The jQuery underpinnings knows when it’s make a cross-origin request and modifies it accordingly. The problem is the server, in this case,
api.github.comdoes not allow CORS requests.The server would have to respond with (at minumum):
Access-Control-Allow-Origin: * (or the host in which your page is being served)Since you likely do not own github, you’ll have to either write a server-side proxy OR see if github can provide you with a JSONP call (which jQuery is happy to make for you as well).
MDN Documentation on Access-Control
EDIT
That being said, if you need to modify a request made by jQuery through backbone, there is no need to override the
syncmethod. Use jQuery’s$.ajaxSetupmethod to add any additional headers, set types, etc. Just make sure you run the$.ajaxSetupmethod in the same context or closure as the.save(),.fetch()or.destroy()is going to run or you won’t get the work being performed in$.ajaxSetup