2

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.

Sukanta Paul
  • 784
  • 3
  • 19
  • 36
  • have you tried to add a error function to the then? ``.then(function(){ // success function}, function(){ console.log(arguments); // error function})``. then can take 1 argument to be function (success only) or 2 arguments to be function (success and error) – mtizziani Feb 27 '17 at 15:56
  • Are you using form submit to pass your data to server side? – Angela Amarapala Feb 27 '17 at 16:06

1 Answers1

4

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

digijap
  • 164
  • 9