简体   繁体   English

无法使用 Angular HttpInterceptor 捕获 401 状态代码

[英]Unable to catch 401 status code with Angular HttpInterceptor

I have created an HTTP response interceptor which checks for the 401 status code.我创建了一个 HTTP 响应拦截器来检查 401 状态代码。 If the code is 401, it is supposed to simply write in browser console, but this does not work.如果代码是 401,它应该简单地写在浏览器控制台中,但这不起作用。 It doesn't even seem to catch it.它甚至似乎没有抓住它。

App.js:应用程序.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');
            }]);

Index.html索引.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测试控制器.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);
    });

});

The access token is stored in local storage from a previous landing/login page.访问令牌存储在先前登陆/登录页面的本地存储中。 What I'm trying to achieve is to redirect the user to this landing page if his token isnt valid anymore, or if he doesn't have one.我想要实现的是,如果他的令牌不再有效或他没有令牌,则将用户重定向到此登录页面。

With a valid token, no problem, i successfully retrieve data from the api.使用有效令牌,没问题,我成功地从 api 检索数据。 But when I manually change the stored token, in order to trigger a 401, nothing is written in the browser console.但是当我手动更改存储的令牌以触发 401 时,浏览器控制台中没有任何内容。

I'm sure that it's a 401 Unauthorized Reponse, because I checked it in Chrome network observer.我确定这是 401 未经授权的响应,因为我在 Chrome 网络观察器中检查过它。 Here's the only thing that i get:这是我唯一得到的:

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.

And here are the requests ( yes, because sometime I have only one request in the list, and when I refresh the page it sometime append that there is two of them )这是请求(是的,因为有时我在列表中只有一个请求,当我刷新页面时它有时会附加有两个请求)

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

Here's what i was talking about, for this time, when i refreshed the page i had two requests done, but it's strange because i only do one request in my code.这就是我所说的,这一次,当我刷新页面时,我完成了两个请求,但这很奇怪,因为我在我的代码中只做了一个请求。

And sometime, after a few refresh i only have:有时,经过几次刷新后,我只有:

Name    Status     Type     Initiator
stuff    401       xhr       Other

But in both cases, I never had anything written in the console, which proves me that the 401 error has been caught.但是在这两种情况下,我都没有在控制台中写入任何内容,这证明我已经捕获了 401 错误。

Thank you, and sorry for bad english !谢谢,抱歉英语不好!

Try to add request and requestError functions (just in case, I know it is optional):尝试添加 request 和 requestError 函数(以防万一,我知道它是可选的):

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

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

I changed an url but it works.我更改了一个网址,但它有效。 Please also notice my comments.还请注意我的评论。 Error 401 will never be catched in response() because interceptor always redirects 401 to responseError().错误 401 永远不会在 response() 中被捕获,因为拦截器总是将 401 重定向到 responseError()。

Try replacing console.log with $log.log.尝试用 $log.log 替换 console.log。 You'll need to add it to the dependencies just like $q and $location.您需要将它添加到依赖项中,就像 $q 和 $location 一样。

as an example:举个例子:

(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');
  }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM