使用CORS但没有凭据的骨干集合

时间:2017-07-19 08:58:43

标签: backbone.js cors

我有一个用骨干制作的应用程序。当集合尝试同步时,我收到以下错误:

XMLHttpRequest cannot load https://someserver/menu.json. The value of 
the 'Access-Control-Allow-Origin' header in the response must not be 
the wildcard '*' when the request's credentials mode is 'include'. 
Origin 'http://www.otherdomain.com' is therefore not allowed access. 
The credentials mode of requests initiated by the XMLHttpRequest is 
controlled by the withCredentials attribute.

集合只是指定模型和网址,并且只需要一个简单的解析。

我尝试覆盖同步方法,如下所示:

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

我在app初始化时运行此功能。但是,错误仍然相同。我尝试了不同的组合(withCredentials:false,删除了行withCredentials等)但没有成功。

服务配置为提供服务'。'。

有没有不同的方法来解决这个问题?

重新配置服务或禁用浏览器安全性不是一种选择。

1 个答案:

答案 0 :(得分:0)

只有当xhrFields为空时,您的代码才会执行​​,可能不是。

尝试类似

的内容
if (!options.xhrFields) {
  options.xhrFields = {};
}
options.xhrFields.withCredentials = false;

这只会暂时解决问题。在实际应用程序中,您将需要凭据,并且您应该在服务器中添加域的白名单以实际解决问题