我对AngularJS非常陌生,现在已经花费3天时间找到一种处理401状态的方法。我尝试使用拦截器、$http、$resource等方式...但没有任何效果。我的应用在同一服务器上调用JSONP调用。当错误发生时,它被捕获在错误回调函数中。但是状态永远是0,响应是未定义的。
首先,我尝试了这个拦截器
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.responseInterceptors.push(['$q', function($q) {
return function(promise) {
return promise.then(function(response) {
console.log('success in interceptor');
return response;
}, function(response) {
console.log('error in interceptor');
console.log(response);
if (response.status === 401) {
response.data = {
status: false,
description: 'Authentication required!'
};
return response;
}
return $q.reject(response);
});
}
}]);
}]);
其次,在控制器中使用 $resource 也进行了尝试。
$scope.fetchData = function(fromDate, toDate){
Cancel.get({from: fromDate, to: toDate, perPage: 99999},
function(data){
$scope.cancels = $scope.filteredCancels = data.data;
$scope.search();
},
function(response) {
$scope.errorMessage = '<h4>Error : '+response.status+'</h4>';
window.location = "/";
});
};
第三,尝试使用 $http 而不是 $resource
$scope.fetchData = function(fromDate, toDate){
$http.jsonp('http://host:8900/api/cancellations?callback=JSON_CALLBACK')
.success(function(data, status, headers, config) {
console.log(status);
})
.error(function(data, status, headers, config) {
console.log(status);
};
这是用于JSONP调用的头信息
Request URL:http://host:8900/api/cancellations?callback=angular.callbacks._0
Request Method:GET
Status Code:401 Unauthorized
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Cookie:__utma=149207145.339724205.1374885003.1377550245.1378313049.3; __utmc=149207145; __utmz=149207145.1378313049.3.2.utmcsr=cyphersmart.qc3deva.electricmail.com:8900|utmccn=(referral)|utmcmd=referral|utmcct=/; remember_username=elie.kim%40electricmail.com; PHPSESSID=gdoemlp5jltqq62etc5gfuh653; cookie=cookiecheck; __utma=1.789184132.1378340585.1378499390.1378504453.10; __utmb=1.3.10.1378504453; __utmc=1; __utmz=1.1378340585.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Host:host:8900
Referer:http://host:8900/reports/cancels/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Ubuntu Chromium/25.0.1364.160 Chrome/25.0.1364.160 Safari/537.22
Query String Parametersview sourceview URL encoded
callback:angular.callbacks._0
Response Headersview source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Date:Fri, 06 Sep 2013 22:02:13 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=20
Pragma:no-cache
Server:nginx/0.7.65
Transfer-Encoding:chunked
我找不到处理未经授权的状态码401的方法,我已经尝试了所有的方法。如果你能给我一些提示或者建议,我将非常感激。
responseInterceptors
在 1.2 版本中发生了变化。 - TheSharpieOne