如何使用 CORS 和 Backbonejs 向 API 发出 ajax 请求 [英] How to make an ajax request to an API using CORS and backbonejs
问题描述
我正在处理一个backbone.js 项目,我正在调用我的github 存储库.我已经引导加载了我的集合和模型,因此它们在我的页面构建后就存在,但是当我调用 model.fetch() 时,我收到此消息:(将 :username 替换为用户名)
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 函数,但我不完全确定如何.到目前为止,这是我的代码(这是在我的 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.
服务器必须响应(至少):
The server would have to respond with (at minumum):
Access-Control-Allow-Origin:*(或提供页面的主机)
由于您可能不拥有 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 通过主干发出的请求,则无需覆盖 sync
方法.使用 jQuery 的 $.ajaxSetup
方法添加任何其他标题,设置类型等.只要确保在与 .save()
、.fetch()
相同的上下文或闭包中运行 $.ajaxSetup
方法code> 或 .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 向 API 发出 ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!