AngularJS HTTP 401 无响应

AngularJS no response on HTTP 401

我正在尝试捕获发生 401(令牌过期)的事件,以便我可以向 re-authorise 具有新令牌的用户发送请求。我的问题是响应为 401:

时未达到响应代码
angular.module('app')
       .factory('authInterceptor',

function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
        console.log('not 401');
      }
      return config;
    },
    response: function (response) {
      console.log(response.status);
      if (response.status === 401) {
        // handle the case where the user is not authenticated
        console.log('401 !!!!!!!');
      }
      return response || $q.when(response);
    }
  };
});

其他人通过不包括 WWW-Authenticate header 解决了这个问题,我试过了,但仍然没有调用响应函数。我正在考虑使用另一个状态代码来解决该问题,但我不想这样做。

当响应为401时,这是一个错误(所有4x都是错误)。 您应该使用 属性 responseError 来检查。

'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    }

检查 $http 文档 https://docs.angularjs.org/api/ng/service/$http