Home >Web Front-end >JS Tutorial >Angular uses interceptors to uniformly process http requests and response example codes
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!