Handle HTTP 302 response from proxy in angularjs

I had the same problem in my app.
You can’t really “catch” a 302 redirect response. The browser catches it before Angular get it’s hand on it. so actually, when you do receive your response – it is already too late.

The bad news: it’s not a problem in the angular platform. The xmlHttpRequest do not support this kind of behaviour, and the browser act before you can do anything about it.
reference: Prevent redirection of Xmlhttprequest

The good news: there are many ways to bypass this problem, by intercepting the response- and find some way to recognize that it’s your lovable 302. This is a hack, but it’s the best you can do at the moment.

So.
For example, in my app, the redirect was back to the login.html page of the app, and in the app i got the response with a 200 status and the data of the response was the content of my login.html page.
so in my interceptor, i checked if the result is a string (usually not! so- no efficiency prob..) and if so- checked if it’s my login.html page. that way, i could catch the redirect and handle it my way.

yourApp.factory('redirectInterceptor', ['$location', '$q', function($location, $q) {
    return function(promise) {
        promise.then(
            function(response) {
                if (typeof response.data === 'string') {
                    if (response.data.indexOf instanceof Function &&
                        response.data.indexOf('<html id="ng-app" ng-app="loginApp">') != -1) {
                        $location.path("/logout");
                        window.location = url + "logout"; // just in case
                    }
                }
                return response;
            },
            function(response) {
                return $q.reject(response);
            }
        );
        return promise;
    };
}]);

Then insert this interceptor to your app. something like this:

$httpProvider.responseInterceptors.push('redirectInterceptor');

good luck.

Leave a Comment