【发布时间】:2017-09-04 23:14:54
【问题描述】:
我正在使用一个非常基本的 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。
在我的项目中,将使用$rootScope.$on('event:auth-forbidden', function(r) {...}); 在全球范围内捕获 403。这就是为什么 REST 服务器只会在未找到某些东西时抛出 404,当用户没有权限和/或未登录时抛出 403,只有在登录失败时才会抛出 401。
那么我如何在$http 上捕获 401?.then 承诺不是仅用于返回 200,.catch 不是用于其他所有返回!= 200?
我正在使用 angularJS v1.6.4 和 angular-http-auth v1.5.0。
【问题讨论】:
-
这篇旧文章我认为是一个很好的参考。您可以将 .success .error 链接起来。要不然。您可以使用 .then 并检查响应对象,它应该有一个状态代码属性,指示您是否应该拒绝或解决承诺 weblog.west-wind.com/posts/2014/Oct/24/…
-
你使用
angular-http-auth模块吗? -
... 或注册了任何全局
$http拦截器? -
是的,我有
angular-http-auth版本为 v1.5.0。我正在使用http-auth-interceptor模块,以便在成功登录的then链中使用authService.loginConfirmed(response.data);。但除此之外,我只听event:auth-forbidden、event:auth-loginConfirmed和event:auth-loginRequired和$rootScope.$on(...);。 -
我的 Angular 版本中不再提供
.success或.error。
标签: javascript angularjs rest