本文部分轉自:http://blog.csdn.net/magiclr/article/details/49643277
最近開發中遇到一個問題,需要在模塊A發出的請求頭信息中添加token屬性。如圖所示:
簡單說明一下情況:模塊A所請求的後臺是獨立的,url爲”/isearch/…”。模塊A發出的POST請求請求頭信息中必須包含token,其它模塊的請求頭信息中不需要token。token是從Cookie中獲取的,Cookie是在模塊A發出的第一個請求中返回的,如圖所示
以下是解決辦法:
module.config(['$httpProvider',function($httpProvider){
$httpProvider.interceptors.push('authInterceptor');
}])
.factory('authInterceptor', function($rootScope, $cookies){
return {
request: function(config){
config.headers = config.headers || {};
if(new RegExp("isearch").test(config.url) && "POST" == config.method){
if($cookies.get('token')){
config.headers['token'] = $cookies.get('token');
}
}
return config;
},
responseError: function(response){
// ...
}
};
})
順便總結一下angularjs設置請求頭信息的幾種方法(原文:http://blog.csdn.net/magiclr/article/details/49643277):
1、在http服務的在服務端發送請求時,也就是調用http()方法時,在config對象中設置請求頭信息:示例如下:
$http.post('/somePath' , someData , {
headers : {'token' : getCookie('token')}
}).success(function(data, status, headers, config) {
//...
}).error(function(data, status, headers, config ) {
//...
});
這種方法的好處就是針對不同路徑的請求,可以個性化配置請求頭部,缺點就是,不同路徑請求都需要單獨配置。
設置某個get請求禁用瀏覽器緩存
$http.get(settingUrl,{
headers : {'Expires':0,'Cache-Control':'no-cache','Pragma':'no-cache'}
}).success(function(results){
});
2、第二種設置請求頭信息的方式就是在$httpProvider.defaults.headers屬性上直接配置。事例如下:
myModule
.config(function($httpProvider) {
$httpProvider.defaults.headers.post= { 'token' : getCookie('token') }
})
$httpProvider.defaults.headers有不同的屬性,如common、get、post、put等。因此可以在不同的http請求上面添加不同的頭信息,common是指所有的請求方式。
這種方式添加請求頭信息的優勢就是可以給不同請求方式添加相同的請求頭信息,缺點就是不能夠爲某些請求path添加個性化頭信息。
3、第三種設置請求頭信息的地方是$httpProvider.interceptors。也就是爲請求或相應註冊一個攔截器。這種方法就是上面用到的。
首先定義一個服務:
myModule.factory('authInterceptor', function($rootScope, $cookies){
return {
request: function(config){
config.headers = config.headers || {};
if($cookies.get('token')){
config.headers['token'] = $cookies.get('token');
}
return config;
},
responseError: function(response){
// ...
}
};
})
上面的config貌似就是請求頭,可以根據config,爲特定的請求方式添加請求頭信息。
然後把上面定義的服務註冊到$httpProvider.interceptors中。
.config(function($httpProvider){
$httpProvider.interceptors.push('authInterceptor');
})
這樣,對於每次請求,不論是get還是post、put。我們都會在請求頭信息中加入authorization屬性。這種方式在處理驗權、授權方面很有用的。
說明:文中getCookie(‘token’)爲自定義函數
function getCookie(name) {
if (name != null) {
var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
return value ? decodeURIComponent(value[1]) : null;
}
}