【发布时间】: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