javascript - AngularJS $http redirect on status code - Stack Overflow

I have a angular application with many $http request and i want redirect the users on the login page if

I have a angular application with many $http request and i want redirect the users on the login page if the server session expires (get 401). Does anyone know a solution witch works for all $http without adding .error() on every $http?

I have a angular application with many $http request and i want redirect the users on the login page if the server session expires (get 401). Does anyone know a solution witch works for all $http without adding .error() on every $http?

Share Improve this question edited Mar 30, 2015 at 14:36 Muhammad Reda 27.1k14 gold badges98 silver badges106 bronze badges asked Mar 30, 2015 at 9:25 ChristophChristoph 2,0531 gold badge27 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

It would be better if you could use an http interceptor to redirect all detected 401 errors.

// 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);
            }
        }
    };
});

You can use Interceptors to achieve this. From Mean.js source code

angular.module('users').config(['$httpProvider',
function($httpProvider) {
    // Set the httpProvider "not authorized" interceptor
    $httpProvider.interceptors.push(['$q', '$location', 'Authentication',
        function($q, $location, Authentication) {
            return {
                responseError: function(rejection) {
                    switch (rejection.status) {
                        case 401:
                            // Deauthenticate the global user
                            Authentication.user = null;

                            // Redirect to signin page
                            $location.path('signin');
                            break;
                        case 403:
                            // Add unauthorized behaviour 
                            break;
                    }

                    return $q.reject(rejection);
                }
            };
        }
    ]);
}
 ]);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745368086a4624674.html

相关推荐

  • javascript - AngularJS $http redirect on status code - Stack Overflow

    I have a angular application with many $http request and i want redirect the users on the login page if

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信