Backbone.js的不会让跨主机的请求? [英] Backbone.js won't make cross-host requests?

查看:199
本文介绍了Backbone.js的不会让跨主机的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩骨干在我的浏览器控制台,并运行到一个跨域的问题,我想不通。

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

我连接到presumably正确的主机实现CORS因为原始XHR请求返回预期的JSON:

The host I'm connecting to presumably correctly implements CORS because a raw XHR request returns the expected 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进度事件与响应的正确数据)

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

但是当我做了与骨干以下的浏览器不喜欢它:

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

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();

(返回 XMLHtt prequest无法加载http://example.com:3000/entities/item/产地的http://本地主机:8000不会被允许访问控制允许-Origin。

有什么我需要做的,告诉骨干与CORS工作?这个错误似乎已经到来之前,浏览器甚至提出的要求,所以我不认为这是一个服务器配置错误。

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.

推荐答案

我希望这些人帮助(我没有尝试尚未):

1。<一个href=\"http://naleid.com/blog/2012/10/29/overriding-backbone-js-sync-to-allow-cross-origin-resource-sharing-cors/\">Overriding Backbone.js的同步,允许跨源

I hope one of these helps (I didn't try yet):
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, model, options);
  };
})();

2。对于Backbone.js的跨域CORS支持

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

这篇关于Backbone.js的不会让跨主机的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆