Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在AngularJS中设置应用程序范围的HTTP头_Javascript_Mvvm_Angularjs - Fatal编程技术网

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

Javascript 在AngularJS中设置应用程序范围的HTTP头,javascript,mvvm,angularjs,Javascript,Mvvm,Angularjs,有没有办法在angular.module('myApp',[]).config()之外设置$httpProvider标题 在登录用户后,我从服务器获得一个Auth令牌,我需要将它作为HTTP头添加到所有以下请求中 $http.defaults.headers.common['Auth-Token'] = 'token'; 似乎headers()规范化了键名。您可以为angular1.0.x使用默认标题: $http.defaults.headers.common['Authentication

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

在登录用户后,我从服务器获得一个Auth令牌,我需要将它作为HTTP头添加到所有以下请求中

$http.defaults.headers.common['Auth-Token'] = 'token';

似乎
headers()
规范化了键名。

您可以为angular1.0.x使用默认标题:

$http.defaults.headers.common['Authentication'] = 'authentication';
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');
});
或为angular1.1.x+请求拦截器:

$http.defaults.headers.common['Authentication'] = 'authentication';
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');
});

由于工厂/服务是单例的,只要您不需要在服务实例化后动态更改“身份验证”值,就可以使用。

添加到@Guria和@Panga的上述响应中

config.headers['X-Access-Token'] = $window.sessionStorage.token;
可以在头中使用x-access-token作为JWT(jsonwebtoken)。
当用户第一次进行身份验证时,我将JWT存储在会话存储器中。

您能详细说明一下规范化密钥名称的含义吗?使用headers()方法获取头时,密钥“Auth Token”将小写并变为“Auth Token”。这很让人困惑。@lucassp可能是这样的-我喜欢这种服务。谢谢有点困惑。如何将其集成到我的应用程序中?我是否需要作为依赖项列出,然后使用
$httpProvider
而不是
$http
?将$httpProvider插入挂起应用程序模块的配置方法中。提供者是在通过Angular将服务注入控制器等之前配置服务的一种方式。@AakilFernandes这只是一种配置。你可以直接注入$http,这很奇怪。当我使用$http.defaults.headers.common时,我得到一个错误405(方法不允许)。我不确定这里的问题是否是webapp2。