Javascript 在 AngularJS 中设置应用程序范围的 HTTP 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14183025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting application wide HTTP headers in AngularJS
提问by lucassp
Is there a way to set the $httpProviderheaders outside of angular.module('myApp', []).config()?
有没有办法在$httpProvider外面设置标题angular.module('myApp', []).config()?
I'm getting an Auth-Token from the server after I login the user, and I need to add it as a HTTP Header to all following requests.
登录用户后,我从服务器获取了一个 Auth-Token,我需要将它作为 HTTP 标头添加到所有后续请求中。
采纳答案by lucassp
$http.defaults.headers.common['Auth-Token'] = 'token';
It seems headers()normalizes the key names.
它似乎headers()规范了键名。
回答by Leonardo Zanivan
You can use default headers for angular 1.0.x:
您可以为 angular 1.0.x使用默认标头:
$http.defaults.headers.common['Authentication'] = 'authentication';
or request interceptor for angular 1.1.x+:
或为 angular 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');
});
Since factories/services are singletons, this works as long as you do not need to dynamically change your 'authentication' value after the service has been instantiated.
由于工厂/服务是单例,只要您不需要在服务实例化后动态更改“身份验证”值,就可以使用此方法。
回答by Pranjal Singi
Adding to above responses of @Guria and @Panga
添加@Guria和@Panga的上述回复
config.headers['X-Access-Token'] = $window.sessionStorage.token;
One can use x-access-token in header as JWT(jsonwebtoken). I store JWT in the session storage when a user authenticate first time.
可以在标头中使用 x-access-token 作为 JWT(jsonwebtoken)。当用户第一次进行身份验证时,我将 JWT 存储在会话存储中。

