0

When running an angularjs application, the user access may be withdrawn from the server side. In this case, every request results in a http 302 redirect and a login html (no partial) page. Since angular does expect whatever it was requesting in case the access would still be given, it breaks as it may expect a json string but gets the html login page.

Is there anything I can do do catch this event (listen to redirects, figure out whether html is returned, etc) and do a "hard" refresh of the redirect url?

orange
  • 7,755
  • 14
  • 75
  • 139

2 Answers2

1

Since you can't interfere an ajax 302 response and redirect to an error page, you will need to be a little creative.

You can add a header or a different response code to your relevant responses and add an interceptor on the client end.
The interceptor is a module that every ajax request\response goes throught.
You can add code that will look for that header and simple perform a $window.location.href to the login page.

Read here about interceptors.
Check this example out - It handles 401 responses.

Community
  • 1
  • 1
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • +1 this is probably a cleaner way than checking the data result for whether it's an html page. Can only accept one answer, but thanks anyway. – orange Apr 09 '15 at 08:26
  • @orange - I don't care about accepted answers, but doing it Nano's way is not really the good way (even though it works). You need a way to identify unauthorized requests and handle them generically - That means you must use a client interceptor. Now I don't know what you are doing on your server but you don't want to 302 on errors like some server side frameworks do (.net's forms authentication). You simply want to return a 401 and redirect on the client. – Amir Popovich Apr 09 '15 at 08:29
  • Agree, I've added a comment at @Nano's answer that points readers to the client interceptor. – orange Apr 09 '15 at 08:36
0

If I get you right you are talking about the $http Service from AngularJS.

If thats the point, you could transform the response by yourself and check if its valide JSON like this:

$http({
    url: '...',
    method: 'GET',
    transformResponse: function (reponse) {
        var ret = [];//if the return stays empty, the repsonse may be HTML
        try {
            ret = JSON.parse(reponse);
        } catch (error) {
            //here you could check for the error
        }
        return ret;
    }
}).success(function(answer){
    if(answer.length === 0){//its empty, so its probably HTML
        $window.location.reload();//refresh page here
        return;
    }
    //its JSON with content!
});
Nano
  • 1,398
  • 6
  • 20
  • 32
  • 1
    I just found an answer after posting. It's similar to your suggestion, but a bit more generic (see post from @Ofer Segev http://stackoverflow.com/questions/18737674/handle-http-302-response-from-proxy-in-angularjs). – orange Apr 09 '15 at 08:22