简体   繁体   中英

google maps tracks api - send request using node js

In order to access the google maps tracks API, i have access token sent by Google's OAuth 2.0 Authorization Server. Now i need to send this access token with every http request i made to google map tracks API. Where should i put this access token in http request ?. I tried to put in headers as 'X-Access-Token' : 'myaccesstoken', but am getting response from api as below.

body: '{\\n "error": {\\n "errors": [\\n {\\n "domain": "global",\\n "reason": "required",\\n "message": "Login Required",\\n "locationType": "header",\\n "location": "Authorization"\\n }\\n ],\\n "code": 401,\\n "message": "Login Required"\\n }\\n}\\n' }

I referred google map tracks API official documentation https://developers.google.com/maps/documentation/tracks/auth , but unable to solve this error.

below is the code am using to authenticate with Google's OAuth 2.0 Authorization Server, and code to send request to google map tracks 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);
        });
    }
});

Found the solution, access token should be put in header : { 'Authorization' : 'myaccesstoken' }, so after changes, code will look like below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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