Add access_token in backbone.js

2019-05-01 16:24发布

In my REST server, it's requiring the access_token to be present in every request. i.e. in POSTing data, access_token needs to be submitted together with the attributes.

How do I configure backbone.js to add access_token to every GET, PUT, POST and DELETE request?

Thanks.

2条回答
孤傲高冷的网名
2楼-- · 2019-05-01 17:02

Backbone uses jQuery/Zepto for AJAX requests, so you can use the functionality available in those libraries.

To add custom headers to all XHR calls made by jQuery, you can use the jQuery.ajaxSend event, which is triggered before every ajax request, and modify the jqXHR it receives as an argument.

Edit based on OP's comments:

Probably the simplest way to modify the sent data is to override the Backbone.sync function. You could wrap the native implementation, and add the required property there:

var nativeSync = Backbone.sync;
Backbone.sync = function (method, model, options) {
  //for POST/PUT requests, add access token to the request
  if(model && (method === 'create' || method === 'update')) {

    var data = _.extend(model.toJSON(), {
      access_token: 'token'
    });

    options.data = JSON.stringify(data);
  }
  //call the native Backbone.sync implementation
  nativeSync(method, model, options);
};
查看更多
疯言疯语
3楼-- · 2019-05-01 17:21

Okay, I think I found a way how to do it in jQuery.

$.ajaxSetup (
   {
      data: { access_token: 'my_access_token' }
   }
);
查看更多
登录 后发表回答