简体   繁体   English

全局设置angularjs $ http标头

[英]Setting angularjs $http headers globally

I have a webapp with multiple controllers. 我有一个带有多个控制器的webapp。 I'm setting the defaults headers of the $http service in a callback in one of my controllers (via http.defaults.headers.common['headername'] ). 我正在我的一个控制器的回调中设置$http服务的默认标头(通过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? 我是否必须为每个控制器设置它们或者只有一次?

You should use one of two methods: 您应该使用以下两种方法之一:

Set $http.defaults.headers in run block eg 在运行块中设置$ http.defaults.headers,例如

 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM