Angularjs 处理角度响应
我有一个简单的api和一个授权点 当我请求api时,如果令牌无效(令牌在五分钟后失效),我会得到401 我知道我可以拦截401,例如Angularjs 处理角度响应,angularjs,Angularjs,我有一个简单的api和一个授权点 当我请求api时,如果令牌无效(令牌在五分钟后失效),我会得到401 我知道我可以拦截401,例如 app.factory("HttpErrorInterceptorModule", ["$q", "$rootScope", "$location", function($q, $rootScope, $location) { var success = function(response) { // pass th
app.factory("HttpErrorInterceptorModule", ["$q", "$rootScope", "$location",
function($q, $rootScope, $location) {
var success = function(response) {
// pass through
return response;
},
error = function(response) {
if(response.status === 401) {
// dostuff
}
return $q.reject(response);
};
return function(httpPromise) {
return httpPromise.then(success, error);
};
}
]).config(["$httpProvider",
function($httpProvider) {
$httpProvider.responseInterceptors.push("HttpErrorInterceptorModule");
}
]);
但是我希望捕获请求并对其排队,如果成功,则显示登录表单,然后更改令牌(它是一个头)并再次执行请求。您可以以稍微不同的方式使用$httpInterceptor。若您想在登录后将用户重定向到用户实际失败的页面,则需要在某个服务中缓存失败的请求,然后在登录后将用户重定向到某个位置(我相信逻辑连接到您的登录) 但是您可能需要有一些测试端点来保护您的控制器免受不受限制的访问,您可能希望使用resolve 因此,在这种情况下,您将收到与限制访问ProctedEndpoint而不是页面相关的错误 为了解决这个问题,我使用marker param(或header)来找出登录后应该重定向用户的位置 下面是您的httpInterceptor的示例
angular.factory('httpInterceptor', function ($q, $rootScope, $log, someService) {
return {
request: function (config) {
return config || $q.when(config)
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if (response.status === 401) {
//here I preserve login page
someService
.setRestrictedPageBeforeLogin(
extractPreservedInfoAboutPage(response)
)
$rootScope.$broadcast('error')
}
return $q.reject(response);
}
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
});
angular http auth模块提供了一种服务,该服务可以拦截请求并请求它们在用户登录后重新发送 该服务还触发以下事件,以便您可以收听它们并决定在屏幕上显示什么
- 事件:需要身份验证登录
- 事件:身份验证登录已取消
- 事件:aut登录已确认
您能补充一个解释吗?以及如何对请求进行排队关于我将把它们放入缓存的请求队列,失败请求上的某个对象,然后重定向,然后在成功登录后检索。我将在15分钟内修复答案。如果我存储在
request
functionconfigs.push(config)
中,然后在response
functionconfigs.pop()
,我如何识别每个响应属于请求?您不需要存储每个请求,因为您将耗尽内存。我将存储失败的配置,对于每个控制器,我将有一个解析部分,其中包含对auth的测试请求,您可以在其中传递有关所需页面的信息。如果此请求失败,目标页面将不会被加载->您将显示您的登录页面,然后有关于请求页面的信息,您将进入页面。谢谢!我不明白为什么响应不能用相同的“响应”方法处理,因为它是401而不是200