谷歌地图跟踪api - 使用节点js发送请求

时间:2015-09-10 06:50:26

标签: node.js google-maps

为了访问Google地图跟踪API,我有来自Google的OAuth 2.0授权服务器发送的访问令牌。现在我需要发送此访问令牌与每个http请求我谷歌地图轨道API。我应该在http请求中将此访问令牌放在哪里?我尝试将标题放入' X-Access-Token' :' myaccesstoken',但是我从api那里得到了回复,如下所示。

正文:' {\ n"错误":{\ n"错误":[\ n {\ n"域" :"全球",\ n"原因":"必需",\ n"消息":"需要登录" ,\ n" locationType":"标题",\ n"位置":"授权" \ n} \ n \ n,\ n&n& #34;代码":401,\ n"消息":"需要登录" \ n} \ n} \ n' }

我提到谷歌地图跟踪API官方文档https://developers.google.com/maps/documentation/tracks/auth,但无法解决此错误。

下面是我用来验证Google的OAuth 2.0授权服务器的代码,以及用于向Google地图跟踪API发送请求的代码。

var jwt = new googleapis.auth.JWT(client_email, keyFile, null, scopes, null);

jwt.authorize(function(jwtErr, tokens){
    if(jwtErr){
        return;
    }
    else{
        headers = {
            'content-type' : 'application/json',
            'X-Access-Token' : tokens.access_token
        };

        options = {
            url : 'https://www.googleapis.com/tracks/v1/geofences/list',
            headers : headers,
            method : 'POST',
        };
        request(options, function(error, response, body){
            if(error){
                return; 
            }
            console.log(response);
        });
    }
});

1 个答案:

答案 0 :(得分:0)

找到解决方案,应该放入访问令牌 标题:{'授权' :' myaccesstoken' }, 所以在更改之后,代码将如下所示。

var jwt = new googleapis.auth.JWT(client_email, keyFile, null, scopes, null);

jwt.authorize(function(jwtErr, tokens){
    if(jwtErr){
        return;
    }
    else{
        headers = {
            'content-type' : 'application/json;charset=utf-8',
            'content-length': Buffer.byteLength(data),
            **'Authorization' : tokens.access_token**
        };

        options = {
            host: 'www.googleapis.com',
            path: '/tracks/v1/entities/create',
            headers : headers,
            method : 'POST',
        };

        var post_req = https.request(options, function(res){
              res.setEncoding('utf8');
              res.on('data', function (chunk) {
                  console.log('Response: ' + chunk);
              });
        });
        post_req.on('error', function(error_msg){
            console.log(error_msg);
        });
        post_req.write(data);
        post_req.end();
    }
});
相关问题