angular 用攔截器統一處理http請求和響應 比如加token


想使用angularjs里的htpp向后台發送請求,現在有個用戶唯一識別的token想要放到headers里面去,也就是{headres:{'token':1}}

index.html里引入以下js:

angular.module('app.factorys',[])
    .factory('httpInterceptor',['$q','$injector','$localStorage',function ($q,$injector,$localStorage) {
        var httpInterceptor = {
            'responseError' : function(response) {
                // ......
                return $q.reject(response);
            },
            'response' : function(response) {
                if (response.status == 21000) {
                    // console.log('do something...');
                }
                return response || $q.when(response);
            },
            'request' : function(config) {
                config.headers = config.headers || {};
                if ($localStorage.token) {
                    config.headers.token = $localStorage.token;
                    // config.headers['X-Access-Token'] = $localStorage.token;
                };

                return config || $q.when(config);

                return config;
            },
            'requestError' : function(config){
                // ......
                return $q.reject(config);
            }
        };
        return httpInterceptor;
    }])
 

在app里注入factory后,在config里面配置

.config(['$httpProvider',function(){
    $httpProvider.interceptors.push(httpInterceptor);
}])

 

 

如果你的代碼並未做拆分,可以直接在config里面寫攔截器

 $httpProvider.interceptors.push(['$q','$injector','$localStorage',function ($q,$injector,$localStorage) {
            var httpInterceptor = {
                'responseError' : function(response) {
                    // todo...
                    return $q.reject(response);
                },
                'response' : function(response) {
                    if (response.status == 21000) {
                        // console.log('do something...');
                    }
                    return response || $q.when(response);
                },
                'request' : function(config) {
                    config.headers = config.headers || {};
                    if ($localStorage.token) {
                        config.headers.ut = $localStorage.token; //把你登錄接口返回給你的token存到$localStorage里面,在這里取就好了
                        // config.headers['X-Access-Token'] = $localStorage.token;
                    };

                    return config || $q.when(config);
                    // return config;
                },
                'requestError' : function(config){
                    // todo...
                    return $q.reject(config);
                }
            };
            return httpInterceptor;
        }]);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM