2016-11-18 72 views
0

我正在尝试使用jwt访问api。当我发布凭证时,我从服务器获得id_token。我解压缩它,但是当我尝试使用Bearer将中的令牌添加到下一个请求时,令牌显示为undefined,因此接收500内部错误为“JWT字符串必须包含两个周期字符,找到:0”。显示在画面在AngularJS,JWT授权标题未定义

我的代码以下控制台错误:

angular.module('myApp', []).controller('myCtrl', function($scope, $http){ 
//$scope.tok = ''; 
$http({ 
    method : "POST", 
    url : "http://server.com/api/authenticate", 
    data: '{"username":"username","password":"password","rememberMe":true}', 
    headers:{"Content-Type": "application/json;charset=UTF-8", 
      } 
    }).then(
    function mySuccess(response){ 
     $scope.token = response.data.id_token; 
    }, function myError(response){ 
     console.log(response); 
    }); 

$http({ 
    method: "GET", 
    url: "http://server.com/api/account", 
    data: '', 
    headers:{"Authorization": "Bearer " + $scope.token, 
      "Content-Type": "application/json;charset=UTF-8"} 
}).then(
    function mySuccess(response){ 
     console.log(response); 
    }, function myError(response){ 
     console.log(response); 
    }); 

}); 

enter image description here

回答

2

当然,这是因为你的令牌返回你的第二个要求后。 在飞,你可以解决它像这样:

angular.module('myApp', []).controller('myCtrl', function($scope, $http){ 
//$scope.tok = ''; 
$http({ 
    method : "POST", 
    url : "http://server.com/api/authenticate", 
    data: '{"username":"username","password":"password","rememberMe":true}', 
    headers:{"Content-Type": "application/json;charset=UTF-8", 
      } 
    }).then(
    function mySuccess(response){ 
     $scope.token = response.data.id_token; 
     $http({ 
      method: "GET", 
      url: "http://server.com/api/account", 
      data: '', 
      headers:{"Authorization": "Bearer " + $scope.token, 
       "Content-Type": "application/json;charset=UTF-8"} 
     }).then(
      function mySuccess(response){ 
       console.log(response); 
      }, function myError(response){ 
       console.log(response); 
      }); 

     }); 
    }, function myError(response){ 
     console.log(response); 
    }); 
+0

谢谢瓦西里斯;) –

+0

不客气! –