我仍然遇到 AngularJS 1.5.3 的问题。
我正在尝试使用$http
请求中的 401 Unauthorized 错误做一些逻辑。
这里的代码。
...
var req = {
url: 'http://localhost:8080/news',
method: 'GET'
};
$http(req)
.then(successHandler)
.catch(function(message) {
console.log(message);
if(message.status === "401") {
// logic here
}
});
...
在没有auth令牌的情况下运行这段代码后,我得到了:
Object {data: null, status: -1, config: Object, statusText: ""}
浏览器知道是401,并在console.log
之前显示错误。
发生了什么事?
答案 0 :(得分:0)
我建议您查看documentation of angular's $http和angular's $q (angular promising)。尝试使用.then()
- 方法,它需要两个参数,第一个是http成功时的回调,第二个是http-error。所以你可以这样写:
$http.get('http://localhost:8080/api/news').then(
function(resp) {
//whatever happens when everything is fine
}, function(error) {
console.log(message);
if(error === "401") {
// logic here
}
}
);
此外,$http.get()
是method: 'GET'
的简写,promise.catch(errorCallback)
是promise.then(null, errorCallback)
最好的问候。