2017-08-05 72 views
0

我正在使用Angular 1.6.4,Express 4.15.2和快速會話。 我想通過檢查req.session.user參數的存在來捕獲用戶是否未經授權訪問特定路由。如果他不是,我想發送401響應狀態並更改Angular狀態。在AngularJS 401上獲得響應對象

問題是我沒有得到任何響應對象來檢查狀態。 我曾嘗試使用攔截器,註銷error.response.body,註銷一切真的要找出它在哪裏,我失去了響應對象。

這裏有一些代碼,任何幫助將不勝感激!

表示:

app.get('/update', sessionCheck, function(req, res) { 
    res.send('session'); 
}); 

function sessionCheck(req, res, next){ 
    if(req.session.user) { 
     next(); 
    } else { 
     console.log('before'); 
     return res.status(401).send('Unauthorized'); 
     console.log('after'); 
    } 
} 

角:

.state('update', { 
    url: '/update', 
    views: { 
    "": { 
     templateUrl: 'templates/update.html', 
     controller: function($http) { 
     return $http.get('/update').then(function(response) { 
      console.log('Ok response' + response); 
     }, function(error) { 
      console.log('Error response' + error.response.body); 
     }); 
     }, 
    }, 
    "carousel": { 
     templateUrl: "templates/carousel.html" 
    }, 
    "footer": { 
     templateUrl: "templates/footer.html" 
    } 
    } 
}) 

network screen

+0

你在網絡標籤請求中看到了什麼? – mehulmpt

+0

@mehulmpt在屏幕上添加了 – amamagen

+0

的鏈接,您的回覆正確無誤。您在您的nodejs代碼中發送401未授權的未授權用戶,因此它在您的網絡選項卡中顯示爲 – mehulmpt

回答

0

您是否嘗試過這樣做使用攔截器?

你可以試試這樣:

anyModule.service('yourInterceptor', function($q) { 
var service = this; 

service.responseError = function(response) { 
    if (response.status == 401){ 
     //do something 
    } 
    return $q.reject(response); 
}; 

})

,在這裏,我們正在處理responseError注意。

您需要您註冊攔截太在配置功能:

$httpProvider.interceptors.push('yourInterceptor'); 

你可以看到這個關於這個攔截器的更多信息:

Capture HTTP 401 with Angular.js interceptor

UPDATE:

你也可以用這種方式註冊一個攔截器:

app.factory("YourInterceptor", ["$q", "$rootScope", "$location", 
function($q, $rootScope, $location) { 
    var success = function(response) { 
     //do something 
     return response; 
    }, 
    error = function(response) { 
     if(response.status === 401) { 
       // do something 
     } 

     return $q.reject(response); //reject on error 
    }; 

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

然後您註冊這樣你的攔截器(在模塊的配置):

$httpProvider.responseInterceptors.push("YourInterceptor"); 

注意,你推攔截器在responseInterceptors。這項工作給我。

+0

我有。沒有條件,只是console.log('字符串')。在其他路線工作,但在這一個沒有出現。 – amamagen

+0

您可以嘗試用'響應'替換'responseError'並查看攔截器中記錄的內容。請注意,如果您通過'回覆'來做到這一點,您不能僅僅拒絕所有的承諾。 –

+0

'angular.module('app。提供商) 。服務('authInterceptor」,[ '$ Q', '$注射器', '$位置', 函數($ Q,$注射器,$位置) { 返回{ 請求:功能(配置){ 的console.log( '1'); 返回配置; }, requestError:功能(配置){ 的console.log( '2'); 返回配置; }, 響應:功能(res){console.log('3'); return res; }, responseError:function(res){ console.log('4'); return res; } } }])' '/ update'沒有提供任何內容。 – amamagen