ottercoder ottercoder - 5 months ago 11
AngularJS Question

$http request. Response comes to success function even when status code is 401

In my Angular app I have a login function. But when I send wrong credentials and response come with status 401: Bad Credentials (there's even response.status = 401) it still goes to success.

So I'm getting $notify "Success login and then html error page in my interceptor. That's confusing. I'm not sure what I've done to create this mess.

this.getTokenCustom = function (user) {
$http.post('/login',
JSON.stringify({username: user.username, password: user.password}))
.then(
function success(response) {
localStorage.setItem('token', response.data.token);
$.notify({message: "Success login"},{type:'success'});
$state.go('roles');
},
function error(data) {
console.log(data);
$.notify({message: data.data.message},{type:'danger'});
}
);
};


UPD

this.getTokenCustom = function (user) {
$http.post('/login',
JSON.stringify({username: user.username, password: user.password}))
.then(
function success(response) {
localStorage.setItem('token', response.data.token);
$.notify({message: response.status + " Success login"},{type:'success'});
$state.go('roles');
},
function error(data) {
console.log(data);
$.notify({message: data.data.message},{type:'danger'});
}
);
};


screen

Answer

The likely cause of this is that you may have a custom interceptor that doesn't handle error conditions properly.

This post can point you on the right direction: http://www.jamessturtevant.com/posts/AngularJS-HTTP-Service-Success-Handler-400-Response-Code-and-Interceptors/

To quote the post:

When you handle the requestError or the responseError for a interceptor and you wish to pass the error on to the next handler you must use the promise api to reject the message:

$httpProvider.interceptors.push(function($q) {
    return {
        'requestError': function(rejection) {
            // handle same as below
        },

        'responseError': function(rejection) {
            if (canRecover(rejection)) {
                // if you can recover then don't call q.reject()
                // will go to success handlers
                return responseOrNewPromise;
            }

            // !!Important Must use promise api's q.reject()
            // to properly implement this interceptor
            // or the response will go the success handler of the caller
            return $q.reject(rejection);
        }
    };
});

A similar issue to yours was reported on Angular's Github repository and the issue had to do with a custom interceptor not handling error conditions properly.