問題是,如果用戶沒有有效的JWT,我想限制對特定路由的訪問並顯示登錄頁面。我只想告訴我,在AngularJs和NodeJs中我很新。因此,在短期我有AngularJs路由認證
LoginCtrl:
$scope.login = function(username, password){
UserSvc.login(username, password)
.then(function(response){
$scope.$emit('login', response.data);
$window.location.href = '#/';
}, function(resp){
$scope.loginError = resp.data.errors;
});
}
我上升的事件,在ApplicationCtrl該事件由該
$scope.$on('login', function(_, user){
$scope.currentUser = user
})
這是很酷,它的工作完美擦肩而過,問題是,我在我的route.js中有一些路線,我想對其進行一些驗證。
$routeProvider
.when('/', {controller:'PostsCtrl', templateUrl: 'posts.html'})
.when('/register', {controller:'RegisterCtrl', templateUrl: 'register.html'})
.when('/login', {controller:'LoginCtrl', templateUrl: 'login.html'})
.otherwise({redirectTo: '/login'});
在nodejs中我可以很容易地放置一箇中間件,但我怎麼能在AngularJs中做到這一點。所以現在發生的事情是,當我登陸頁面時,我可以按登錄。它將我重定向到登錄頁面,然後當我按Posts時,Nodejs返回401,因爲我沒有有效的JWT,但僅在控制檯中顯示。 AngulrJs沒有做任何事情。
你正在尋找的答案是攔截器。檢查這個模塊的角度。 https://github.com/witoldsz/angular-http-auth它從服務器捕獲錯誤401,併爲您提供選項。 – SayusiAndo