angularJS中的攔截器

這裏我將的攔截器,是關於前端項目的請求的攔截器,基於angularJS中的httpProvider的。

有沒有這樣一種場景,在使用ajax請求的時候,服務端需要驗證header中的token和cookie,所以每次請求的時候都需要加上這個token,cookie不用加,每次請求的時候瀏覽器都會幫你帶上,所以你就需要在有ajax的地方都添加一段向header中寫token的代碼,是不是覺得挺鬧心的?

別怕,我來幫你解決這個問題。

在angularJS官方api中$http處有這麼一段話:

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptorsarray. The factory is called and injected with dependencies (if specified) and returns the interceptor.

這段話的意思就是通過使用promise對象(處理回調的一個非常使用的對象)和$httpProvider.interceoters這個數組,按照該數組的指定格式,就可以對請求的過程進行控制,數據的格式是這樣的:

{
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
 
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}



相信一些小夥伴看了這個數據已經有些感覺了,因爲angular 的$http是封裝了ajax的,所以可以通過$httpProvider控制請求的過程。

附上我在程序中的代碼加深理解:

var App = angular.module('app',[]);
App.factory('authInterceptor',['$q','authService','mAlert',function($q,authService,mAlert){
return {
'request':function(config){
var token = (authService.getToken());
config.headers['author'] = token;
return config ||$q.when(config);
},
'responseError' :function(resError) {
if(resError.status == 404){
mAlert.alert({
title:'系統提示',
body:'請求資源未找到'
})
}
return $q.reject(resError);
}
}
}])
.provider('authService',function(){
var token="zhumin",
self = this;
self.$get = function(){
return {
getToken:function(){
return token;
}
}
}
}).config(['$httpProvider',function($httpProvider){
$httpProvider.interceptors.push('authInterceptor')
}])


 mAlert是我自己封裝的一個模態框,可以忽略。

factory返回了一個$httpProvider.interceptors數據規定的格式,用於當request之前爲header添加token,reponseError用與服務端返回錯誤狀態時的操作。provider相當於封裝了一個類,用於factory中調用。

在config中將攔截器注入數據中,就可以實現在整個引用程序中的ajax請求的header中帶上token,效果不錯吧~

效果圖如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章