我需要拦截每个Ajax请求,以验证服务器是否响应了401 Unauthorized,因为会话过期了,并重定向到登录页面,这样用户就不会认为应用程序停止工作了。我可以使用JQuery进行如下操作:
$( document ).ajaxComplete(function( event, xhr, settings ) {
if(xhr.errorCode == 401 || xhr.responseText === "unauthorized") {
location.href = "/Login";
}
});我怎么能用棱角的JS做这件事?
发布于 2015-08-07 15:21:53
可以在应用程序配置()上设置$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);
}
};
}]);
}])发布于 2015-08-07 14:47:10
使用httpInterceptor。很类似的问题是不久前的answered。然后,您应该对'response' hanndler感兴趣,并在其中添加您的特定逻辑。
发布于 2015-08-07 14:44:03
创建一个用于进行所有调用的函数,您只需在一个地方处理错误,而不是在多个地方处理错误。
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
})
}https://stackoverflow.com/questions/31880398
复制相似问题