add request header on backbone

后端 未结 10 2092
伪装坚强ぢ
伪装坚强ぢ 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:38
    Object.save(
      {'used': true}
      {headers: {'Access-Token': 'access_token'}}
    )
    
    0 讨论(0)
  • 2020-12-04 09:42
    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.setRequestHeader with every sync call.

    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.

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

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

        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
        });
    
    0 讨论(0)
提交回复
热议问题