我预计错误的请求会落在 $http#error 中定义的函数中,但那并没有发生。相反,我必须创建一个拦截器。即使我知道状态码应该是 404,响应中返回的状态码是 0。
$http({url: "myurl", method: "GET"}).success(
function(data, status, headers, config) {
if (data.ret_code === 200) {
//do something
}
}).error(function(data, status, headers, config) {
//NEVER GETS HERE ON BAD REQUEST!!
});
这是拦截器:
var interceptor = ['$q', function ($q) {
function success(response) {
return response;
}
function error(response) {
//ALWAYS 0!
var status = response.status;
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
1-这是为什么? 2-有没有办法在 $http#error 中捕获错误的请求? 3-有没有办法获取实际的 404 状态代码?
最佳答案
我知道 Android 中有一个“错误”,从浏览器缓存传送的文件给出状态码 0。
Github 问题: https://github.com/angular/angular.js/issues/1720
黑客修复(来自同一页面):
// fix status code for file protocol (it's always 0) and 0 status code for http(s) protocol on Android devices
status = (protocol == 'file') ? (response ? 200 : 404) : (response && status == 0 && window.navigator.userAgent.indexOf('Android') !== -1 ? 200 : status);
关于AngularJS $http,错误处理,拦截器和响应状态码 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24922615/