Home  >  Article  >  Web Front-end  >  Angular uses interceptors to uniformly process http requests and response example codes

Angular uses interceptors to uniformly process http requests and response example codes

零下一度
零下一度Original
2017-06-26 13:41:371413browse

I want to use htpp in angularjs to send requests to the background. Now there is a token uniquely identified by the user that I want to put in the headers, which is {headres:{'token':1}}

index Introduce the following js into .html:

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;
    }])

After injecting the factory into the app, configure it in the config

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

The above is the detailed content of Angular uses interceptors to uniformly process http requests and response example codes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn