Handle redirects in angularjs $http

后端 未结 3 924
粉色の甜心
粉色の甜心 2020-12-05 18:43

I\'m using angularjs http service in my app, and I noticed this in the website:

If the AJAX call succeeds (the server sends back an HTTP code between

3条回答
  •  攒了一身酷
    2020-12-05 19:17

    Please note that this is specific to my project.

    Goal: Catch 302 status code and redirect the page (to login in my case).

    Result: In firebug, I could see that the response code is 302 but then I found out that angularjs returns 200 by simply printing the value of status (response.status). So at first you'd thought that you're hopeless. But in my case, what I did was get the data (response.data), look for the string that could be only found in my login page. Then that's it. problem solved :D

    The idea was taken here.

    Here's the code

    app.factory('redirectInterceptor', function($q,$location,$window){
        return  {
            'response':function(response){
            if (typeof response.data === 'string' && response.data.indexOf("My Login Page")>-1) {
                console.log("LOGIN!!");
                console.log(response.data);
                $window.location.href = "/login.html";
                return $q.reject(response);
            }else{
                return response;
            }
            }
        }
    
        });
    
        app.config(['$httpProvider',function($httpProvider) {
            $httpProvider.interceptors.push('redirectInterceptor');
        }]); 
    

提交回复
热议问题