2014-05-21 29 views
0

我正在設置AngularJS和角度ui路由器的授權。 如果用戶試圖訪問需要授權的路由,服務器將返回401狀態碼。在401狀態碼上重定向頁面

我已經創建了一個HTTP響應攔截器來檢查401狀態碼。 如果代碼是401,它應該重定向到登錄頁面,但這不起作用。 它捕獲了401,但不重定向。下面是攔截器的代碼:

app.config(['$httpProvider', function ($httpProvider) { 
    // This is just for to check for XHR requests on the server 
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; 

    $httpProvider.responseInterceptors.push(['$q', '$location', function ($q, $location) { 
     return function (promise) { 
      return promise.then(

       // Success: just return the response 
       function (response) { 
        return response; 
       }, 

       // Error: check the error status to get only the 401 
       function (response) { 
        if (response.status === 401) 
         $location.url('/users/login'); 

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

編輯:這似乎是工作,如果我不喜歡這樣寫道:

$timeout(function() { $location.url('/users/login'); }, 0);

我想,把它最後在執行堆棧和變化執行上下文。有沒有人知道更多關於這個,或者如果這確實有用或似乎是這樣?

回答

0

我終於解決了它,但我仍然不知道爲什麼它沒有工作。無論如何,我只好用這個來重定向:(狀態轉變)

$injector.get('$state').transitionTo('users.login');

0

我添加相同的問題。所以我改變了我的代碼使用$ location.path(不是URL)

$location.path("https://stackoverflow.com/users/login"); 

你可以試穿

angular.module('yourApp').config(function ($httpProvider) { 

    var logsOutUserOn401 = ['$q', '$location', function ($q, $location) { 
    var success = function (response) { 
     return response; 
    }; 

    var error = function (response) { 
     if (response.status === 401) { 
     //redirect them back to login page 
     $location.path('/login'); 

     return $q.reject(response); 
     } 
     else { 
     return $q.reject(response); 
     } 
    }; 

    return function (promise) { 
     return promise.then(success, error); 
    }; 
    }]; 

    $httpProvider.responseInterceptors.push(logsOutUserOn401); 
}); 

(來源:http://arthur.gonigberg.com/2013/06/29/angularjs-role-based-auth/

+0

這似乎不適用於我。我懷疑它可能與執行上下文,return語句或兩者有關。 – ptf

0

我把它與

工作
$window.location.href='...' 
0

這是我們如何在我們的項目中增加了一個響應的攔截器。它爲我們工作。

$httpProvider.interceptors.push(function($q, $rootScope, $location, 
             $cookieStore) { 
            return { 
             'responseError' : function(
               rejection) { 
              var status = rejection.status; 
              var config = rejection.config; 
              var method = config.method; 
              var url = config.url; 

              if (status == 401) { 

               $rootScope.shouldRedirect = true; 
               $rootScope.urlAttempted = url; 

               $location 
                 .path("/login"); 

              } else if (status == 403) { 

               $location 
                 .path("/accessForbidden"); 

              } else { 

              } 

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