我正在使用一个非常基本的 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)
提示。但是没有 success
或 catch
作为输出。也没有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 响应而失败和缓冲的所有待处理请求时。
关于javascript - AngularJS promise 捕获 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46045018/