Set defaults header on AngularJS but don't use it on one specific request

后端 未结 4 1221
半阙折子戏
半阙折子戏 2020-12-10 01:26

For sending OAuth2 token I am setting up defaults header on AngularJS like this:

$http.defaults.headers.common[\'Authorization\'] = \'Bearer \' + access_toke         


        
相关标签:
4条回答
  • 2020-12-10 01:32

    When you make your call with $http, you can override defaults headers by providing them directly in your request config:

    $http({method: 'GET', url: '/someUrl', headers: {'Authorization' : 'NewValue'} }).success();
    

    Otherwise you could transform your request using the transformRequest parameter, still in your $http config. See doc :

    transformRequest – {function(data,headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.

    This way you could delete an header for a single request before it's being send:

    $http({method: 'GET', 
           url: '/someUrl', 
           transformRequest: function(data,headersGetter){ //Headers change here } 
    }).success();
    
    0 讨论(0)
  • 2020-12-10 01:44

    For latecomers, whilst the solution might have worked - you actually shouldn't need to use transformRequest for this.

    The Angular docs for the $http service actually have this exact situation covered:

    To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, Use the headers property, setting the desired header to undefined. For example:

     var req = {  
          method: 'POST',  
          url: 'http://example.com',  
          headers: {  
               'Content-Type': undefined  
          },  
          data: { 
               test: 'test' 
          } 
     }
    
     $http(req).success(function(){...}).error(function(){...});
    
    0 讨论(0)
  • 2020-12-10 01:51

    While the $httpProvider can override $http the use of intereceptors are 1 way of handling this, I end up doing it this way

    function getMyStuff(blah) {
    
            var req = {
                method: 'GET',
                url: 'http://...',
                headers: {
                    'Authorization': undefined
                }
            }
            return $http(req)
                .then(function(response) {
                    return response.data;
                });
    
    
    }
    
    0 讨论(0)
  • 2020-12-10 01:54

    Angular 1.4.0 can no longer modify request headers using transformRequest:

    If one needs to dynamically add / remove headers it should be done in a header function, for example:

    $http.get(url, {
      headers: {
        'X-MY_HEADER': function(config) {
          return 'abcd'; //you've got access to a request config object to specify header value dynamically
        }
      }
    })
    
    0 讨论(0)
提交回复
热议问题