网络编程 
首页 > 网络编程 > 浏览文章

angular 用拦截器统一处理http请求和响应的方法

(编辑:jimmy 日期: 2026/9/24 浏览:3 次 )

想使用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请求和响应的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:jquery实现放大镜简洁代码(推荐)
下一篇:原生JS发送异步数据请求
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。