在我的 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'});
}
);
};
最佳答案
造成这种情况的可能原因是您可能有一个无法正确处理错误情况的自定义拦截器。
这篇文章可以为您指明正确的方向: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/