【问题标题】:Backbone fetch: Headers are not set while performing backbone fetch with custom header data主干提取:使用自定义标头数据执行主干提取时未设置标头
【发布时间】:2014-01-09 19:20:06
【问题描述】:

我正在开发一个涉及从外部 API 获取数据的主干应用程序。 我的应用程序的域是 product.site1.com,而 API 的域是 api.site1.com。

这就是我的模型和集合的外观

var pModel = new Backbone.Model.extend({});
var pCollection = new Backbone.Collection.extend({
                      model: pModel,
                      url: 'api.site1.com/product'
});

视图如下所示

var pView = new Backbone.View.extend({
         initialize: function() {
                var _this = this;
                var pCollectionVar = new pCollection();
                pCollectionVar.fetch({
                           dataType: 'jsonp',
                           beforeSend: _this.sendAuthentication,
                           success: function(collection, response, options) {
                                   console.log(collection);
                           },
                           error: function(collection, xhr, options) {
                                   console.log("error");
                           }
                     });
                } 
         sendAuthentication: function(xhr) {
            xhr.setRequestHeader('customKey1', 'ABCD');
            xhr.setRequestHeader('customKey2', '1234');
        }
});

执行此操作时,我的应用程序向 API 服务器发出 get 请求,而我没有在服务器端获取标头数据。我也没有在我的 chrome 开发工具中看到为请求设置的这些自定义标头。

编辑: 选项http://api.site1.com/product 405(不允许的方法)jquery-1.10.2.js:8706

OPTIONS http://api.site1.com/product 无效的 HTTP 状态代码 405 jquery-1.10.2.js:8706

XMLHttpRequest 无法加载 http://api.site1.com/product。无效的 HTTP 状态代码 405(索引):1

这些是我在执行请求时遇到的错误。

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    如果你想像你一样使用 sendAuthentication 它应该是一个全局函数:

    pCollectionVar.fetch({
      dataType: 'jsonp',
      beforeSend: sendAuthentication,
      success: function(collection, response, options) {
        console.log(collection);
      },
      error: function(collection, xhr, options) {
        console.log("error");
      }
    });
    
    function sendAuthentication(xhr){
       //Code goes here
    }
    

    虽然这会污染全局范围,但我会使用命名空间:

    var MyApplication = {};
    MyApplication.sendAuthentication = function(xhr){ //code inside}.
    
    
    pCollectionVar.fetch({
      dataType: 'jsonp',
      beforeSend: MyApplciation.sendAuthentication,
      success: function(collection, resp){//rest...}
    

    编辑

    here 所述,jsonp 不是 ajax 调用,不能这样对待

    【讨论】:

    • 好的,我了解这里的范围界定问题。即使在调整范围之后,也没有设置标题。 jsonp和自定义header一起使用会不会有问题?
    • @sree jsonp 不是 ajax 调用,请参阅回答中的编辑
    • 感谢您的澄清。我已在问题中包含错误。
    猜你喜欢
    • 1970-01-01
    • 2012-10-15
    • 2012-04-22
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多