繁体   English   中英

在AngularJS中,JWT授权标头未定义

[英]in AngularJS, JWT Authorization header is undefined

我正在尝试使用jwt访问一个api。 当我使用凭据发布时,我从服务器获取了id_token 我提取了它,但是当我尝试使用Bearer将令牌添加到Authorization header的下一个请求时,令牌显示为undefined ,因此收到500 Internal Error,因为“ JWT字符串必须恰好包含2个句点字符。找到:0” 。 控制台错误如图所示

我的代码如下:

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);
    });

});

在此处输入图片说明

当然会发生,因为您的令牌在第二次请求后返回。 您可以即时解决此问题:

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);
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM