如何使用CORS和backbonejs做出一个Ajax请求的API [英] How to make an ajax request to an API using CORS and backbonejs
问题描述
我工作的一个Backbone.js的项目,我打电话给我的github回购。我有我的类别和模式引导加载,以便它们的存在,一旦我的网页建成,但是当我打电话model.fetch()我得到这个消息:(替代:用一个用户名用户名)
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.
我读过一些消息 POST1 ,的post2 ,他们提到修改backbone.sync功能,但我不完全知道如何。这是我的code到目前为止,(这是我的Backbone.Router):
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();
},
谢谢!
推荐答案
CORS是在后端启用。 jQuery的基础知道什么时候它是做一个跨域请求,并相应地修改它。问题是服务器,在这种情况下, api.github.com
不允许CORS请求。
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.
服务器必须与回应(在minumum):
The server would have to respond with (at minumum):
访问控制 - 允许 - 产地:*(或在您的网页被提供服务的主机)
既然你可能不拥有github上,你就不得不要么写一个服务器端的代理服务器或看github上可以为您提供一个JSONP调用(这jQuery是乐意让你也一样)。
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).
修改
这就是说,如果你需要修改通过骨干网由jQuery的要求,没有必要重写同步
方法。使用 jQuery的 $。ajaxSetup
方法添加任何附加头,集类型,等等。只要确保你运行在相同的情况下或封闭的 $。ajaxSetup
方法 .save( )
, .fetch()
或 .destroy()
将运行或者您不会得到在 $正在执行的工作。ajaxSetup
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
这篇关于如何使用CORS和backbonejs做出一个Ajax请求的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!