[英]How to intercept every Ajax Request with Angular JS
我需要拦截每个Ajax请求,以验证服务器是否以401 Unauthorized
响应,因为会话已过期并重定向到登录页面,因此用户不认为该应用程序停止工作。 我可以使用JQuery通过以下方式执行此操作:
$( document ).ajaxComplete(function( event, xhr, settings ) {
if(xhr.errorCode == 401 || xhr.responseText === "unauthorized") {
location.href = "/Login";
}
});
如何使用Angular JS做到这一点?
您可以在应用程序config()上设置$ interceptor
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$location', '$q', function($location, $q) {
return {
'request': function(request) {
return request;
},
'responseError': function(response) {
if (response.status === 401) {
// do stuff
}
// otherwise, default behaviour
return $q.reject(response);
}
};
}]);
}])
使用httpInterceptor
。 不久前回答了非常类似的问题。 然后,您应该对'response'
hanndler感兴趣,并在其中添加您的特定逻辑。
制作一个用于进行所有调用的函数,您只需要在一个地方处理错误,而不是多个地方
function makeCall(obj, cb) {
$http({
method: obj.method,
url: obj.url,
data: obj.data || {}
}, function(res) {
// non error statuses get handled here
}, function(res) {
// error statuses get handled here
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.