javascript - AngularJS promise 捕获 401

标签 javascript angularjs rest

我正在使用一个非常基本的 angularJS 代码来进行这样的用户登录:

[...]
this.login = function(email, password) {
    promise = $http.post('/login',
            {
                'email': email,
                'password': password
            });
    promise.then(function(response){
            console.log("success");
        }).catch(function(response){
            console.log("catch");
        }).finally(function(response){
            console.log("finally");
        });
    return promise;
};
[...]

当 REST API 生成代码为 200 的响应时,客户端控制台将记录success finally,用户已登录。
当服务器生成带有 403 或 500 代码的响应时,控制台将打印出 catch finally

但是当响应是 401 时,angular 不会打印出任何东西。控制台将保持为空,只有 POST http://127.0.0.1/login 401 (Unauthorized) 提示。但是没有 successcatch 作为输出。也没有finally

在我的项目中,403 将通过 $rootScope.$on('event:auth-forbidden', function(r) {...}); 在全局范围内捕获。这就是为什么 REST 服务器只会在未找到内容时抛出 404,在用户没有权限和/或未登录时抛出 403,仅在登录失败时抛出 401。

那么如何在 $http 上捕获 401?
.then 不是只 promise 返回 200 而 .catch 不是每个其他返回!= 200 吗?

我正在使用 angularJS v1.6.4 和 angular-http-auth v1.5.0。

最佳答案

问题是 angular-http-auth 模块拦截了状态为 401 或 403 的响应:

The $http interceptor does the following: the configuration object (this is the requested URL, payload and parameters) of every HTTP 401 response is buffered and everytime it happens, the event:auth-loginRequired message is broadcasted from $rootScope.

禁用 401 拦截器设置 ignoreAuthModule: true:

Sometimes you might not want the interceptor to intercept a request even if one returns 401 or 403. In a case like this you can add ignoreAuthModule: true to the request config.

该模块为 401 状态创建一个处于待处理状态的新 promise 。响应被缓冲,您有机会调用 authService.loginConfirmed()authService.loginCancelled() 函数。第一个重试之前由于 HTTP 401 响应而失败的所有请求。当第二个取消之前因 HTTP 401 响应而失败和缓冲的所有待处理请求时。

Docs

关于javascript - AngularJS promise 捕获 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46045018/

相关文章:

javascript - 在 then block 中使用类函数

javascript - Fabric JS 用相同的项目(ID)替换对象

javascript - 如何在 javascripts 中按经度纬度距离对数组项进行排序?

javascript - 将索引传递给自定义 orderBy 函数

javascript - 使用 AngularJS 生成新字段

javascript - 在 JSON 中编码日期的最佳实践是什么?

JavaScript RegExp 手动设置索引

javascript - AngularJS:bindonce 的 bo-bind 和翻译过滤器

rest - 释放资源的POST方法-不支持的媒体类型

django - 没有 allauth、rest_auth 和 facebook 用户名的用户