[英]Setting application wide HTTP headers in AngularJS
有沒有辦法在angular.module('myApp', []).config()
之外設置$httpProvider
標題?
我在登錄用戶后從服務器上獲取了一個Auth-Token,我需要將它作為HTTP Header添加到所有后續請求中。
您可以使用角度1.0.x的默認標頭:
$http.defaults.headers.common['Authentication'] = 'authentication';
或請求角度為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');
});
由於工廠/服務是單例,只要您在實例化服務后不需要動態更改“身份驗證”值,這就可以正常工作。
$http.defaults.headers.common['Auth-Token'] = 'token';
似乎headers()
規范化了鍵名。
添加@Guria和@Panga的上述回復
config.headers['X-Access-Token'] = $window.sessionStorage.token;
可以在頭文件中使用x-access-token作為JWT(jsonwebtoken)。 當用戶第一次進行身份驗證時,我將JWT存儲在會話存儲中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.