Setting angularjs $http headers globally

2019-02-16 15:45发布

I have a webapp with multiple controllers. I'm setting the defaults headers of the $http service in a callback in one of my controllers (via http.defaults.headers.common['headername']). However, those headers do not get set in subsequent calls from other controllers. Do I have to set them for each controller I have or is one time enough?

1条回答
The star\"
2楼-- · 2019-02-16 16:16

You should use one of two methods:

Set $http.defaults.headers in run block e.g.

 module.run(function($http) {
  $http.defaults.headers.common.Authorization = 'Basic Token';
});

Use interceptor

var interceptor = function() {
  return {
    'request': function(config) {
      config.headers['Authorization'] = 'Basic Token';
     }
  }
};

angular.module('app', [])
  .config(function ($httpProvider) {
    $httpProvider.interceptors.push(interceptor);
});
查看更多
登录 后发表回答