add request header on backbone

后端 未结 10 2102
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 08:46

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? Tha

相关标签:
10条回答
  • 2020-12-04 09:17

    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).

    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');
        }
    });
    
    0 讨论(0)
  • 2020-12-04 09:20

    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.

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

    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.AuthenticatedModel you have created:

    var Process = Backbone.AuthenticatedModel.extend({
        url: '/api/process',
    
    });
    
    0 讨论(0)
  • 2020-12-04 09:21

    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.sync is doing is creating an ajax request using jQuery. In order to incorporate your Basic HTTP authentication you have a couple of options.

    fetch, save, and destroy all 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:

    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 destroy call you make. Like so:

     fetch({
      beforeSend: sendAuthentication 
     });
    

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

    Hope this helps!

    0 讨论(0)
  • 2020-12-04 09:26

    You could override Backbone sync method.

    #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 )       
    
    0 讨论(0)
  • 2020-12-04 09:29

    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.

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

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

    0 讨论(0)
  • 2020-12-04 09:34

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

    MyCollection.fetch( { headers: {'Authorization' :'Basic USERNAME:PASSWORD'} } );
    
    0 讨论(0)
提交回复
热议问题