2017-02-17 86 views
0

所以我對我的web應用程序進行了身份驗證。這是我的身份驗證控制器。刷新頁面後丟失身份驗證(AngularJS,NodeJS)

myTodoList.controller('authController', function($scope, $rootScope, $http, $location) { 
$scope.user = { username: '', password: '' }; 
$scope.error_message = ''; 

$scope.login = function() { 
    $http.post('/auth/login', $scope.user).success(function(data) { 
     if (data.state == 'success') { 
      $rootScope.authenticated = true; 
      $rootScope.current_user = data.user.username; 
      $location.path('/app'); 
     } else { 
      $scope.error_message = data.message; 
     } 
    }); 
}; 

$scope.register = function() { 
    $http.post('/auth/signup', $scope.user).success(function(data) { 
     if (data.state == 'success') { 
      $rootScope.authenticated = true; 
      $rootScope.current_user = data.user.username; 
      $location.path('/app'); 
     } else { 
      $scope.error_message = data.message; 
     } 
    }); 
}; 

});

這工作正常,我登錄後進行身份驗證或進行新的註冊。但刷新頁面後,我失去了我的身份驗證。我認爲這些線路會產生問題。

var myTodoList = angular.module("myTodoList", ['ngRoute', 'ngResource']).run(function($http, $rootScope) { 
$rootScope.authenticated = false; 
$rootScope.current_user = 'Guest'; 

$rootScope.signout = function() { 
    $http.get('auth/signout'); 
    $rootScope.authenticated = false; 
    $rootScope.current_user = 'Guest'; 
}; 
}); 

在我maincontroller.js頂部我有這個$rootScope.authenticated = false;線。這是我所知道的,但這可能是這樣的一句話,即在刷新之後它應該是錯的而不是真的。我該怎麼做才能解決這個問題?

回答

0

使用localStoragesessionStorage因爲每次當你將刷新頁面的新實例$rootScope將被創建。