想使用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); }])
#
以上是angular用攔截器統一處理http請求和回應實例碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!