angularjs – 处理Angular 401响应
发布时间:2020-12-17 07:25:55 所属栏目:安全 来源:网络整理
导读:我有简单的api和授权点 当我请求api时,如果令牌无效(令牌失效超过五分钟),则获得401. 我知道我可以拦截401例如 app.factory("HttpErrorInterceptorModule",["$q","$rootScope","$location",function($q,$rootScope,$location) { var success = function(resp
我有简单的api和授权点
当我请求api时,如果令牌无效(令牌失效超过五分钟),则获得401. 我知道我可以拦截401例如 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 https://thinkster.io/egghead/resolve/ 为了解决这个问题,我使用了标记参数(或标题)来找出登录后我应该重定向用户的位置. 这是你的httpInterceptor的例子. angular.factory('httpInterceptor',function ($q,$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'); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |