jQuery 在主干上添加请求头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10081728/
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-08-26 08:48:28  来源:igfitidea点击:

add request header on backbone

jquerybackbone.js

提问by jongbanaag

My server has a manual authorization. I need to put the username/password of my server to my backbone request inorder for it to go through. How may i do this? Any ideas? Thank you

我的服务器有手动授权。我需要将我的服务器的用户名/密码放入我的主干请求中,以便它通过。我该怎么做?有任何想法吗?谢谢

回答by shanewwarren

Models in Backbone retrieve, update, and destroy data using the methods fetch, save, and destroy. These methods delegate the actual request portion to Backbone.sync. Under the hood, all Backbone.syncis doing is creating an ajax request using jQuery. In order to incorporate your Basic HTTP authentication you have a couple of options.

在骨干模型中检索,更新和使用方法破坏数据fetchsavedestroy。这些方法将实际请求部分委托给 Backbone.sync。在幕后,Backbone.sync所做的就是使用 jQuery 创建一个 ajax 请求。为了合并您的基本 HTTP 身份验证,您有几个选项。

fetch, save, and destroyall accept an additional parameter [options]. These [options]are simply a dictionary of jQuery request options that get included into jQuery ajax call that is made. This means you can easily define a simple method which appends the authentication:

fetch, save, 和destroy都接受一个额外的参数[options]。这些[options]只是包含在 jQuery ajax 调用中的 jQuery 请求选项的字典。这意味着您可以轻松定义一个简单的方法来附加身份验证:

sendAuthentication = function (xhr) {
  var user = "myusername";// your actual username
  var pass = "mypassword";// your actual password
  var token = user.concat(":", pass);
  xhr.setRequestHeader('Authorization', ("Basic ".concat(btoa(token))));
}

And include it in each fetch, save, and destroycall you make. Like so:

并将其包含在每个fetch, 中save,并destroy调用您 make 。像这样:

 fetch({
  beforeSend: sendAuthentication 
 });

This can create quite a bit of repetition. Another option could be to override the Backbone.syncmethod, copy the original code and just include the beforeSendoption into each jQuery ajax request that is made.

这会造成相当多的重复。另一种选择可能是覆盖该Backbone.sync方法,复制原始代码并将该beforeSend选项包含在每个 jQuery ajax 请求中。

Hope this helps!

希望这可以帮助!

回答by tmaximini

The easiest way to add request header in Backbone.js is to just pass them over to the fetch method as parameters, e.g.

在 Backbone.js 中添加请求头的最简单方法是将它们作为参数传递给 fetch 方法,例如

MyCollection.fetch( { headers: {'Authorization' :'Basic USERNAME:PASSWORD'} } );

回答by Andy Polhill

One option might be to use the jQuery ajaxSetup, All Backbone requests will eventually use the underlying jQuery ajax. The benefit of this approach is that you only have to add it one place.

一种选择可能是使用 jQuery ajaxSetup,所有 Backbone 请求最终都将使用底层 jQuery ajax。这种方法的好处是您只需要将其添加到一处。

$.ajaxSetup({
    headers: { 'Authorization' :'Basic USERNAME:PASSWORD' }
});

Edit 2nd Jan 2018For complex web applications this may not be the best approach, see comments below. Leaving the answer here for references sake.

编辑 2018 年 1 月 2 日对于复杂的 Web 应用程序,这可能不是最佳方法,请参阅下面的评论。将答案留在这里以供参考。

回答by zzart

You could override Backbone sync method.

您可以覆盖 Backbone 同步方法。

#coffeescript
_sync = Backbone.sync
Backbone.sync = (method, model, options) ->
    options.beforeSend = (xhr) ->
        xhr.setRequestHeader('X-Auth-Token_or_other_header' , your_hash_key)
        #make sure your server accepts X-Auth-Token_or_other_header!!
    #calling the original sync function so we only overriding what we need
    _sync.call( this, method, model, options )       

回答by Roman Paraschak

Backbone.$.ajaxSetup({
    headers: {'Authorization' :'Basic USERNAME:PASSWORD'}
});

This code set headers to Backbone ajax, so they will be sent with every Backbone.sync. You will be able to send headers without using xhr.setRequestHeaderwith every sync call.

此代码将标头设置为 Backbone ajax,因此它们将与每个 Backbone.sync 一起发送。您将能够在不使用xhr.setRequestHeader每个同步调用的情况下发送标头。

So you don't need to do the following every time:

因此,您无需每次都执行以下操作:

MyCollection.fetch({ headers: {'Authorization' :'Basic USERNAME:PASSWORD'} } );

You can just do

你可以做

MyCollection.fetch();

Maybe it's kind of hack but it works perfectly for my system.

也许这是一种黑客行为,但它非常适合我的系统。

回答by sebastian-greco

My approach to something like this would be overwrite the sync method in order to add the header before doing the request. In the example you could see that I'm creating a Backbone.AuthenticatedModel, which extends from Backbone.Model.

我的方法是覆盖同步方法,以便在执行请求之前添加标头。在示例中,您可以看到我正在创建一个Backbone.AuthenticatedModel,它从Backbone.Model.

This will impact all methods (GET, POST, DELETE, etc)

这将影响所有方法(GET、POST、DELETE 等)

Backbone.AuthenticatedModel = Backbone.Model.extend({
    sync: function(method, collection, options){
        options = options || {};
        options.beforeSend = function (xhr) {
            var user = "myusername";// your actual username
            var pass = "mypassword";// your actual password
            var token = user.concat(":", pass);
            xhr.setRequestHeader('Authorization', ("Basic ".concat(btoa(token))));
        };
        return Backbone.Model.prototype.sync.apply(this, arguments);
    }

});

Then you have to simple extend the model you need to have authentication, from the Backbone.AuthenticatedModelyou have created:

然后,您必须从Backbone.AuthenticatedModel您创建的模型中简单地扩展您需要进行身份验证的模型:

var Process = Backbone.AuthenticatedModel.extend({
    url: '/api/process',

});

回答by Oleksandr Mishyn

Object.save(
  {'used': true}
  {headers: {'Access-Token': 'access_token'}}
)

回答by ehed

Create a custom sync method that intercepts the calls to Backbone.sync and stuffs your authorization headers in and passes everything else through:

创建一个自定义同步方法,它拦截对 Backbone.sync 的调用并将您的授权标头填入其中并通过其他所有内容:

    REPORTING_API_KEY = 'secretKeyHere';
    CustomSync = function(method, model, options) {
        options.headers = {
            'Authorization' : 'Bearer ' + REPORTING_API_KEY
        };
        return Backbone.sync(method, model, options);
    };

Then overwrite your model's sync with that one:

然后用那个覆盖模型的同步:

    MyModel = Backbone.Model.extend({
        urlRoot: '/api/',
        sync: CustomSync
    });

回答by Umar Asghar

Try to use it. We can use either

尝试使用它。我们可以使用

beforeSend: function(xhr) {
    xhr.setRequestHeader('X-CSRFToken', csrf_token);
},

or

或者

headers: {
    "X-CSRFToken": csrf_token
},

But I would recomment the first option(beforeSend).

但我会推荐第一个选项(beforeSend)。

Here is the working code snippet in my case.

这是我的案例中的工作代码片段。

var csrf_token = this.getCSRFToken();
self.collection.fetch(
{
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRFToken', csrf_token);
    },
    // headers: {
    //     "X-CSRFToken": csrf_token
    // },
    data: {
        "mark_as": "read"
    },
    type: 'POST',
    success: function () {
        if (clickLink) {
            window.location.href = clickLink;
        } else {
            self.unreadNotificationsClicked(e);
            // fetch the latest notification count
            self.counter_icon_view.refresh();
        }
    },
    error: function(){
        alert('erorr');
    }
});

回答by Mohammad Nezarat

  1. In the client side, add this before any server communication:

    $.ajaxSetup({
        xhrFields: {
            withCredentials: true
        },
        async: true
    });
    
  2. In the server side add these headers (PHP):

    header('Access-Control-Allow-Origin: http://your-client-app-domain');
    header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    header('Access-Control-Allow-Credentials: true');
    
  1. 在客户端,在任何服务器通信之前添加:

    $.ajaxSetup({
        xhrFields: {
            withCredentials: true
        },
        async: true
    });
    
  2. 在服务器端添加这些标头(PHP):

    header('Access-Control-Allow-Origin: http://your-client-app-domain');
    header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    header('Access-Control-Allow-Credentials: true');