在AngularJS中有三種方式可以設置請求頭信息:
1、在http服務的在服務端發送請求時,也就是調用http()方法時,在config對象中設置請求頭信息:事例如下:
$http.post('/somePath' , someData , {
headers : {'Authorization' : authToken}
}).success(function(data, status, headers, config) {
//...
}).error(function(data, status, headers, config ) {
//...
});
這種方法的好處就是針對不同路徑的請求,可以個性化配置請求頭部,缺點就是,不同路徑請求都需要單獨配置。
2、第二種設置請求頭信息的方式就是在$httpProvider.defaults.headers屬性上直接配置。事例如下:
ngular.module('app', [])
.config(function($httpProvider) {
$httpProvider.defaults.headers.common = { 'My-Header' : 'value' }
})
$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.authorization = 'Bearer ' + $cookies.get('token');
}
return config;
},
responseError: function(response){
// ...
}
};
})
然后把上面定義的服務注冊到$httpProvider.interceptors中。
.config(function($httpProvider){
$httpProvider.interceptors.push('authInterceptor');
})
這樣,對於每次請求,不論是get還是post、put。我們都會在請求頭信息中加入authorization屬性。這種方式在處理驗權、授權方面很有用的。但是確定就是不能夠為特定的請求方式添加請求頭信息。
上面總共有三種方式設置頭信息,選擇那種方式可以根據自己的需求。