我正在設置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);
我想,把它最後在執行堆棧和變化執行上下文。有沒有人知道更多關於這個,或者如果這確實有用或似乎是這樣?
這似乎不適用於我。我懷疑它可能與執行上下文,return語句或兩者有關。 – ptf