Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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
up vote 4 down vote accepted

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);
            }
        }
    };
});
share|improve this answer
1  
Does this really work? It doesn't seem to actually perform a full page refresh. docs.angularjs.org/guide/$location also states: "It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href." – comecme Apr 17 '15 at 6:55

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);
                }
            };
        }
    ]);
}
 ]);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.