在AngularJS中设置应用程序范围的HTTP标头

luc*_*ssp 47 javascript mvvm angularjs

有没有办法将$httpProvider标题设置在外面angular.module('myApp', []).config()

我在登录用户后从服务器获取Auth-Token,我需要将其作为HTTP Header添加到所有后续请求中.

小智 66

您可以使用角度1.0.x的默认标头:

$http.defaults.headers.common['Authentication'] = 'authentication';
Run Code Online (Sandbox Code Playgroud)

或请求角度为1.1.x +的拦截器:

myapp.factory('httpRequestInterceptor', function () {
  return {
    request: function (config) {

      // use this to destroying other existing headers
      config.headers = {'Authentication':'authentication'}

      // use this to prevent destroying other existing headers
      // config.headers['Authorization'] = 'authentication';

      return config;
    }
  };
});

myapp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
});
Run Code Online (Sandbox Code Playgroud)

由于工厂/服务是单例,只要您在实例化服务后不需要动态更改"身份验证"值,这就可以正常工作.

  • 有点困惑.如何将其集成到我的应用程序中?我是否需要列出作为依赖项,然后使用`$ httpProvider`而不是`$ http`? (2认同)

luc*_*ssp 39

$http.defaults.headers.common['Auth-Token'] = 'token';
Run Code Online (Sandbox Code Playgroud)

它似乎headers()使关键名称正常化.

  • 使用headers()方法获取标头时,"Auth-Token"键变为小写并变为"auth-token".这令人困惑. (4认同)
  • 你能通过规范化关键名称来详细说明你的意思吗? (3认同)