javascript - $http 请求。即使状态代码为 401,也会响应 success 函数

标签 javascript angularjs http

在我的 Angular 应用程序中,我有一个登录功能。但是,当我发送错误的凭据并且响应带有状态 401:错误凭据(甚至有 response.status = 401)时,它仍然会成功。

所以我收到 $notify“成功登录,然后在我的拦截器中出现 html 错误页面。这很令人困惑。我不确定我做了什么来造成这种困惑。

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

最佳答案

造成这种情况的可能原因是您可能有一个无法正确处理错误情况的自定义拦截器。

这篇文章可以为您指明正确的方向:http://www.jamessturtevant.com/posts/AngularJS-HTTP-Service-Success-Handler-400-Response-Code-and-Interceptors/

引用该帖子:

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

类似的issue Angular 的 Github 上报告了您的问题 repository该问题与自定义拦截器未正确处理错误条件有关。

关于javascript - $http 请求。即使状态代码为 401,也会响应 success 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38100992/

相关文章:

html - 当我向服务器发送表单时如何捕获我的发布请求?

java - 跨域认证

javascript - 带百分号的 Google Chart 垂直轴

javascript - 如何从对象内部获取属性名称以创建新的属性名称?

javascript - $q.all - 只取那些已解决的

angularjs + jsonp 返回失败

http - 通过 REST 放置 reportUnit 失败 - Tomcat 错误

javascript - jQuery 遍历

javascript - 创建多个ftp客户端分别从不同的服务器获取文件。这在 Node 中可能吗?

angularjs - 鼠标悬停时打开的 Angular Material 菜单