2016-11-18 126 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

不客氣! –