【问题标题】:Unable to catch 401 status code with Angular HttpInterceptor无法使用 Angular HttpInterceptor 捕获 401 状态代码
【发布时间】:2016-04-09 18:57:24
【问题描述】:

我创建了一个 HTTP 响应拦截器,用于检查 401 状态代码。如果代码是 401,它应该只是在浏览器控制台中编写,但这不起作用。它甚至似乎都没有抓住它。

App.js:

   'use strict';

// Declare app level module which depends on views, and components
var app = angular.module('myApp', []);




app.factory('authHttpResponseInterceptor', ['$q', '$location', function ($q, $location) {
        return {
            response: function (response) {
                if (response.status === 401) {
                    console.log("Response 401");
                }
                else
                {
                    console.log("other response but no 401");
                }
                return response || $q.when(response);
            },
            responseError: function (rejection) {
                if (rejection.status === 401) {
                    console.log("Response Error 401", rejection);
                }
                return $q.reject(rejection);
            }
        }
    }])
        .config(['$httpProvider', function ($httpProvider) {
                //Http Intercpetor to check auth failures for xhr requests
                $httpProvider.interceptors.push('authHttpResponseInterceptor');
            }]);

索引.html

<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

  <div ng-controller="testCtrl"></div>

  <script src="bower_components/angular/angular.js"></script>
  <script src="app.js"></script>
  <script src="testController.js" type="text/javascript"></script>

</body>
</html>

testController.js

app.controller('testCtrl', function ($scope, $http, $timeout) {


    $http.get('http://ec2-54-229-72-240.eu-west-1.compute.amazonaws.com:8080/webservice/api/stuffs/onestuff', {
        headers: {'Authorization': 'Bearer ' + localStorage.getItem('access_token')}
    }).success(function (data) {
        alert(data.id);
    });

});

访问令牌存储在上一个登录/登录页面的本地存储中。 如果他的令牌不再有效,或者他没有令牌,我想要实现的是将用户重定向到这个登录页面。

使用有效的令牌,没问题,我成功地从 api 检索数据。但是当我手动更改存储的令牌时,为了触发 401,浏览器控制台中没有写入任何内容。

我确定这是 401 Unauthorized Reponse,因为我在 Chrome 网络观察器中检查了它。这是我唯一得到的:

XMLHttpRequest cannot load http://ec2-54-229-72-240.eu-west-1.compute.amazonaws.com:8080/webservice/api/students/chat. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. The response had HTTP status code 401.

这是请求(是的,因为有时我在列表中只有一个请求,当我刷新页面时,有时会附加其中两个请求)

Name    Status     Type     Initiator
stuff    200       xhr       angular.js:10765
stuff    401       xhr       Other

这就是我所说的,这次,当我刷新页面时,我完成了两个请求,但这很奇怪,因为我在代码中只执行了一个请求。

有时,经过几次刷新后,我只有:

Name    Status     Type     Initiator
stuff    401       xhr       Other

但是在这两种情况下,我从来没有在控制台中写过任何东西,这证明我已经捕获了 401 错误。

谢谢,抱歉英语不好!

【问题讨论】:

    标签: javascript angularjs xmlhttprequest


    【解决方案1】:

    尝试添加 request 和 requestError 函数(以防万一,我知道这是可选的):

    request: function(config) {
            return config;
          },
    requestError: function(err) {
            $q.reject(err);
          },
    

    http://jsfiddle.net/tjruzpmb/218/

    我更改了一个网址,但它可以工作。还请注意我的 cmets。错误 401 永远不会在 response() 中被捕获,因为拦截器总是将 401 重定向到 responseError()。

    【讨论】:

    • 谢谢♥你节省了我的时间!
    【解决方案2】:

    尝试用 $log.log 替换 console.log。您需要将它添加到依赖项中,就像 $q 和 $location 一样。

    举个例子:

    (function(){
      'use strict';
      angular.module('testModule', [])
             .factory('testFactory', testFactory);
    
      testFactory.$inject = ['$log', '$q', '$location'];
      function testFactory($log, $q, $location){
        $log.log('This will log to the console');
      }
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-18
      • 2017-04-16
      • 2019-06-21
      • 2021-11-26
      • 2016-10-10
      • 2023-04-10
      • 2015-04-15
      • 2018-03-04
      相关资源
      最近更新 更多