【问题标题】:google maps tracks api - send request using node js谷歌地图跟踪 api - 使用节点 js 发送请求
【发布时间】:2015-12-06 08:05:27
【问题描述】:

为了访问谷歌地图跟踪 API,我有谷歌的 OAuth 2.0 授权服务器发送的访问令牌。现在我需要将这个访问令牌与我对谷歌地图轨迹 API 发出的每个 http 请求一起发送。我应该在哪里把这个访问令牌放在 http 请求中?我试图将标头作为“X-Access-Token”:“myaccesstoken”,但我得到了来自 api 的响应,如下所示。

body: '{\n "error": {\n "errors": [\n {\n "domain": "global",\n "reason": "required",\n " message": "需要登录",\n "locationType": "header",\n "location": "Authorization"\n }\n ],\n "code": 401,\n "message": "登录必需"\n }\n}\n' }

我参考了google map track API官方文档https://developers.google.com/maps/documentation/tracks/auth,但是无法解决这个错误。

以下是用于向 Google 的 OAuth 2.0 授权服务器进行身份验证的代码,以及用于向 google map track 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);
        });
    }
});

【问题讨论】:

    标签: node.js google-maps


    【解决方案1】:

    找到解决办法,应该放入access token 标头:{'授权':'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();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2023-02-19
      • 2015-01-06
      • 2014-08-14
      • 2014-10-02
      • 1970-01-01
      • 2016-04-16
      相关资源
      最近更新 更多