我一直在Chrome控制台中使用Backbone,遇到了一个我无法弄清楚的跨域问题.
我正在连接的主机可能正确地实现了CORS,因为原始XHR请求返回了预期的JSON:
var http = new XMLHttpRequest(); http.open('GET','http://example.com:3000/entities/item/15.json',true); http.onreadystatechange = function(evt) { console.log(evt); } http.send();
(在控制台上记录3个XHR进度事件,并在响应中记录正确的数据)
但是当我使用Backbone执行以下操作时,浏览器不喜欢它:
var Item = Backbone.Model.extend({}); var ItemsCollection = Backbone.Collection.extend({ model: Item,url: 'http://example.com:3000/entities/item/' }); var items = new ItemsCollection(); items.fetch();
(返回XMLHttpRequest无法加载http://example.com:3000/entities/item/ .Access-Control-Allow-Origin不允许使用Origin http:// localhost:8000.)
有什么我需要做的告诉Backbone与CORS一起工作吗?这个错误似乎是在浏览器发出请求之前出现的,所以我认为这不是服务器配置错误.
解决方法
我希望其中一个有帮助(我还没试过):
1. Overriding Backbone.js sync to allow Cross Origin
1. Overriding Backbone.js sync to allow Cross Origin
(function() { var proxiedSync = Backbone.sync; Backbone.sync = function(method,model,options) { options || (options = {}); if (!options.crossDomain) { options.crossDomain = true; } if (!options.xhrFields) { options.xhrFields = {withCredentials:true}; } return proxiedSync(method,options); }; })();
2. Cross domain CORS support for backbone.js
$.ajaxPrefilter(function(options,originalOptions,jqXHR) { options.crossDomain ={ crossDomain: true }; options.xhrFields = { withCredentials: true }; });