微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs – 处理Angular 401响应

我有简单的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/
因此,在这种情况下,您将收到与限制访问procprocted端点相关的错误,但不会收到与您的页面相关的错误.

为了解决这个问题,我使用了标记参数(或标题)来找出登录后我应该重定向用户的位置.

这是你的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');
});

原文地址:https://www.jb51.cc/angularjs/141963.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐