add request header on backbone

后端 未结 10 2133
伪装坚强ぢ
伪装坚强ぢ 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: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',
    
    });
    

提交回复
热议问题