How to make an ajax request to an API using CORS a

2019-01-26 02:03发布

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!

2条回答
男人必须洒脱
2楼-- · 2019-01-26 02:29

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

查看更多
Fickle 薄情
3楼-- · 2019-01-26 02:46

I had encountered a similar problem recently and ended up using the mod_proxy. Please refer to: http://blog.lakmali.com/2010/11/apache-proxy-configuration-and-load.html This blog post is pretty clear and straight forward to follow.

mod_proxy supports "https" too, I haven't tried it yet myself, however! Please google more to read about Proxy-choices such as mod_proxy, mod_jk etc.

By going with mod_proxy, we no longer have to make any Cross-Domain calls. Hence, there was no need to worry about IE8/IE9's XDomainRequest hack for performing Cross-Domain requests. [Note: Before using *mod_proxy*, We were trying to over-ride the Backbone.sync to make explicit calls to XDomainRequest instead of jQuery's ajax in order to take care of CORS issues on IE9!]

查看更多
登录 后发表回答