Angularjs没有在.catch()中显示statusText和代码

时间:2016-11-02 11:13:51

标签: angularjs rest http-headers

我仍然遇到 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之前显示错误。

enter image description here

发生了什么事?

1 个答案:

答案 0 :(得分:0)

我建议您查看documentation of angular's $httpangular'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)

的简写

最好的问候。