【发布时间】:2012-12-20 10:03:55
【问题描述】:
有没有办法在angular.module('myApp', []).config() 之外设置$httpProvider 标头?
我在登录用户后从服务器获取了一个 Auth-Token,我需要将它作为 HTTP 标头添加到所有后续请求中。
【问题讨论】:
标签: javascript mvvm angularjs
有没有办法在angular.module('myApp', []).config() 之外设置$httpProvider 标头?
我在登录用户后从服务器获取了一个 Auth-Token,我需要将它作为 HTTP 标头添加到所有后续请求中。
【问题讨论】:
标签: javascript mvvm angularjs
$http.defaults.headers.common['Auth-Token'] = 'token';
似乎headers() 规范了键名。
【讨论】:
您可以为角度 1.0.x 使用默认标题:
$http.defaults.headers.common['Authentication'] = 'authentication';
或 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');
});
由于工厂/服务是单例的,因此只要在服务实例化后不需要动态更改“身份验证”值即可。
【讨论】:
$httpProvider 而不是$http?
添加到@Guria 和@Panga 的上述回复
config.headers['X-Access-Token'] = $window.sessionStorage.token;
可以在标头中使用 x-access-token 作为 JWT(jsonwebtoken)。 当用户第一次进行身份验证时,我将 JWT 存储在会话存储中。
【讨论】: