我有一个带有许多 $http 请求的 angular 应用程序,如果服务器 session 过期(获取 401),我想重定向登录页面上的用户。有谁知道一个解决方案女巫适用于所有 $http 而无需在每个 .error() 上添加 $http

最佳答案

如果您可以使用 http 拦截器重定向所有检测到的 401 错误,那就更好了。

// add an http interceptor via app.config
app.config(function($$httpProvider) {
    $httpProvider.interceptors.push('my401Detector');
});

// interceptor logic.
app.factory('my401Detector', function($location, $q) {
    return {
        responseError: function(response) {
            if(response.status === 401) {
                 $location.path('/login');
                 return $q.reject(response);
            }
            else {
                return $q.reject(response);
            }
        }
    };
});

关于javascript - AngularJS $http 重定向状态码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29342611/

10-12 12:34
查看更多