javascript Backbone.js 不会发出跨主机请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16041172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:01:29  来源:igfitidea点击:

Backbone.js won't make cross-host requests?

javascriptgoogle-chromebackbone.jscross-domain

提问by magneticMonster

I've been playing with Backbone in my Chrome console and running into a cross-domain problem that I can't figure out.

我一直在 Chrome 控制台中使用 Backbone,但遇到了一个我无法弄清楚的跨域问题。

The host I'm connecting to presumably correctly implements CORS because a raw XHR request returns the expected JSON:

我要连接的主机大概正确地实现了 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();

(logs 3 XHR progress events on the console with the correct data in the response)

(在响应中使用正确的数据在控制台上记录 3 个 XHR 进度事件)

But when I do the following with Backbone the browser doesn't like it:

但是当我使用 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();

(returns XMLHttpRequest cannot load http://example.com:3000/entities/item/. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.)

(返回XMLHttpRequest cannot load http://example.com:3000/entities/item/. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.

Is there anything I need to do to tell Backbone to work with CORS? This error seems to have come before the browser even made a request, so I don't think it's a server config error.

我需要做什么才能告诉 Backbone 使用 CORS 吗?这个错误似乎在浏览器发出请求之前就出现了,所以我认为这不是服务器配置错误。

回答by Ikrom

I hope one of these helps (I didn't try yet):
1. Overriding Backbone.js sync to allow Cross Origin

我希望其中之一有帮助(我还没有尝试过):
1.覆盖 Backbone.js 同步以允许跨源

(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, model, options);
  };
})();

2. Cross domain CORS support for backbone.js

2.对backbone.js的跨域CORS支持

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    options.crossDomain ={
        crossDomain: true
    };
    options.xhrFields = {
        withCredentials: true
    };
});

回答by heriberto perez

hey you can use something like:

嘿,你可以使用类似的东西:

 var PostsCollection = Backbone.Collection.extend({
   initialize: function(models, options) {
     //this.id = options.id;
   },
   url: 'http://myapi/api/get_posts/?count=8',
 });

 posts = new PostsCollection();
 posts.fetch({
   dataType: 'jsonp',
   success : function (data) {
     console.log(data);
   }
 });

the key is we need to use 'jsonp'

关键是我们需要使用'jsonp'

回答by magneticMonster

It turns out the URLs I was requesting with Backbone were slightly different than those requested via the XHR (they were missing a queryarg). This caused the server to 500, which doesn't have the CORS headers. Chrome didn't show the HTTP request at all in the network tab of the debug panel, so I was extremely confused.

事实证明,我使用 Backbone 请求的 URL 与通过 XHR 请求的 URL 略有不同(它们缺少 queryarg)。这导致服务器达到 500,它没有 CORS 标头。Chrome 在调试面板的网络选项卡中根本没有显示 HTTP 请求,所以我非常困惑。

Fixing the 500 on the server made this work again.

在服务器上修复 500 使这项工作再次起作用。