Sukanta Paul Sukanta Paul -4 years ago 117
Javascript Question

AngularJS 400 bad request don't give any response

I've searched on Google and stack overflow about similar / even same problems. But I'm new to this none of them gives me any idea of how can I fix up my code.

So, here is my script:

$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';
}
});


Everything is working fine for
200 OK
response. But whenever the login failed the API returns
400 Bad Request
. At this moment, the error looks like it is not even calling the anonymous function with the
response
. Most place a check for 400, 200, 201 etc. was okay & runs perfectly, but why not with 400.

Here is the error as shown in browser console by AngularJS (prettified & removed sensitive data):

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"
}


I'm not a pro in angular.js, an explanation of this behavior and solution would be appreciated.

My target is to display an error message to user that is returned in
data
.

Answer Source

The promise that is returned by $http is resolved by calling the first anonymous function. If a promise is rejected the second anonymous function is called. This should do the trick.

$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;
    }
});

For more examples read the docs

You can read more about promises here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download