Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

backbone.js - How to make an ajax request to an API using CORS and backbonejs

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.com does 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 sync method. Use jQuery's $.ajaxSetup method to add any additional headers, set types, etc. Just make sure you run the $.ajaxSetup method 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...