【问题标题】:AngularJS - How to store JWT token in $localStorageAngularJS - 如何在 $localStorage 中存储 JWT 令牌
【发布时间】:2018-11-24 12:28:56
【问题描述】:

我有这个服务调用 apiService,在那里我可以得到在服务器端生成的令牌。

angular.module('miniMynd')
    .service('apiService', function ($http) {
       return {
         loginUser: function(user){
           $http.post("http://localhost:3010/api/login", user).then(function(response){
             console.log(response.data) * I get the token* 
           })
         },
       }
    });

我的登录Ctrl

$scope.login = function(){
  $apiService.loginUser($scope.credentials); * I pass the crendentials to my function on the client side and i receive a token in the service above*
}

我尝试将令牌放入我的 $localStorage 中,但我收到了一个注入错误,因为只有提供者可以在配置块中注入。

【问题讨论】:

    标签: angularjs jwt token access-token express-jwt


    【解决方案1】:

    您不需要在应用程序中定义任何模块或注入任何其他模块。 在您的应用程序中注入 $window ,然后您可以像这样访问 localstorage 模块

    angular.module('miniMynd', [])
         .controller('loginCtrl', ['$scope', function ($scope) {
        $apiService.loginUser($scope.credentials);
    }]);
    

    然后,

    angular.module('miniMynd')
        .service('apiService', function ($http,$window) {
           return {
             loginUser: function(user){
               $http.post("http://localhost:3010/api/login", user).then(function(response){
                  $window.localStorage.setItem('token', response.data);
               })
             },
           }
        });
    

    你可以像这样检索 localStorage 值

    $window.localStorage.getItem('token');
    

    【讨论】:

    • 萨吉塔兰!!谢谢楼主!!
    • 将令牌存储为计划文本是否安全?
    猜你喜欢
    • 2020-09-08
    • 2021-08-02
    • 2019-02-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2018-12-07
    • 2019-05-06
    相关资源
    最近更新 更多