角度拦截器不拦截401响应

时间:2014-06-04 15:36:27

标签: angularjs

我已创建了http拦截器并附加到我的主应用程序,如下所示:

angular.module('app',['ui.router'])
.factory('AuthInterceptor',function($window,$q){
  return{
    request: function(config){
      console.log("config object is");
      console.log(config);
      if($window.sessionStorage.getItem('token')){
        config.headers['x-access-token']= $window.sessionStorage.getItem('token');
      }
      return config || $q.when(config);

    },

    response: function(response){

     console.log("response object is:");
     console.log(response);

      if (response['status'] >= 400) {
       console.log("Not Authorized.kindly login first");
        $state.transitionTo('login');
      }
      return response || $q.when(response);

    }


  };
})

.config(function($httpProvider){
  $httpProvider.interceptors.push('AuthInterceptor');
});

在服务器端(某些快速代码)我正在检查用户是否被授权,如果没有,我会回复以下代码(仅显示代码子集以保持简洁):

if(!req.user){  
   res.send('Not authorized',400);
}

服务器代码工作正常(我可以在chrome开发人员工具的网络选项卡中看到它) 但是,AuthInterceptor.response()不会被调用。 但请注意,当响应状态为200

时,AuthInterceptor.response()会执行

所以我很困惑..为什么不拦截400种状态?

1 个答案:

答案 0 :(得分:6)

如果响应状态代码超出范围[200-299],则调用responseError拦截器。

您需要提供responseError拦截器:

return {
    request: function (config) {...},
    responseError: function (rejection) {...}
};
相关问题