AngularJS 400错误请求不给出任何响应

时间:2017-02-27 15:49:07

标签: javascript angularjs http-status-code-400

我在谷歌搜索并堆积了类似甚至相同的问题。但我是新手,他们都没有让我知道如何修复我的代码。

所以,这是我的剧本:

$http.post('/authlogin', {
    email: $scope.userdata.email,
    password: $scope.userdata.password
}).then(function(response) {
    console.log(response);
    if (response.status == 400) {
        $scope.errormsg = response.data;
    }
    if (response.status == 200) {
        window.location = '/admin';
    }
});

200 OK响应一切正常。但只要登录失败,API就会返回400 Bad Request。此时,错误看起来甚至没有使用response调用匿名函数。大多数人支票400,200,201等等都没关系。运行得很好,但为什么不用400。

以下是AngularJS在浏览器控制台中显示的错误(经过美化和删除的敏感数据):

Possibly unhandled rejection:
{
    "data": "Invalid email/password combination.",
    "status": 400,
    "config": {
        "method": "POST",
        "transformRequest": [null],
        "transformResponse": [null],
        "jsonpCallbackParam": "callback",
        "url": "/authlogin",
        "data": {
            "email": "####",
            "password": "***"
        },
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8"
        }
    },
    "statusText": "Bad Request"
}

我不是angular.js的专业人士,对此行为和解决方案的解释将不胜感激。

我的目标是向data中返回的用户显示错误消息。

1 个答案:

答案 0 :(得分:2)

$http返回的promise通过调用第一个匿名函数来解决。如果拒绝承诺,则调用第二个匿名函数。这应该可以解决问题。

$http.post('/authlogin', {
    email: $scope.userdata.email,
    password: $scope.userdata.password
}).then(function(successCallback) {       
    if (successCallback.status == 200) {
        window.location = '/admin';
    }
}, function(errorCallback){
    if (errorCallback.status == 400) {
        $scope.errormsg = errorCallback.data;
    }
});

有关更多示例,请阅读docs

您可以阅读有关承诺here

的更多信息