Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

$http.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;

This works great but I don't need this header (I get an error) for one specific request.

Is there a way of excluding defaults header when performing that request?

Thanks!

SOLVED

Thanks to Riron for getting me on a right path. Here's the answer:

$http({
    method: 'GET',
    url: 'http://.../',

    transformRequest: function(data, headersGetter) {
        var headers = headersGetter();

        delete headers['Authorization'];

        return headers;
    }
});
like image 921
Julius Avatar asked May 16 '14 13:05

Julius


3 Answers

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();
like image 57
Riron Avatar answered Oct 19 '22 05:10

Riron


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(){...});
like image 26
Alkie Avatar answered Oct 19 '22 05:10

Alkie


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
    }
  }
})
like image 6
Brent Washburne Avatar answered Oct 19 '22 07:10

Brent Washburne