处理Angular 401响应

rkm*_*max 8 angularjs

我有简单的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");
    }
]);
Run Code Online (Sandbox Code Playgroud)

但是我希望捕获并排队请求并显示登录表单如果成功则更改令牌(它是标题)并再次执行请求

Art*_*mis 6

你可以用另一种方式使用$ httpInterceptor.如果您想在登录后将用户重定向到用户实际失败的页面,您需要在某些服务中缓存失败的请求,然后在登录后将用户重定向到某个地方(我相信您的登录逻辑).

但是您可能需要一些测试端点来保护您的控制器免受不受限制的访问,您可能需要使用解决方法https://thinkster.io/egghead/resolve/ 因此,在这种情况下,您将收到与限制访问proctedted endpoint相关的错误但不是你的页面.

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

这是你的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');
});
Run Code Online (Sandbox Code Playgroud)