Google Analytics Reporting API returning empty obj

2019-07-26 09:40发布

问题:

first question so bear with me.

I am using NodeJS to query the Google Analytics Reporting API. I am able to receive the OAuth 2 token I need, and when I query the API I get a 200 response back. However the payload that returns is an empty object instead of the JSON formatted report response that is the intended goal.

var https = require('https');
var google = require('googleapis');
var key = require('path/to/key');
var jwtClient = new google.auth.JWT(key.client_email,null,key.private_key,'https://www.googleapis.com/auth/analytics.readonly',null);

var getGoogleData = google.analyticsreporting('v4');

var googleTemplates = {"reportRequests":[{"viewId": "######","dateRanges": [{"startDate": "2014-11-01", "endDate": "2014-11-30"}],"metrics": [{"expression": "ga:users"},{"expression": "ga:newUsers"},{"expression": "ga:pageviews / ga:sessions"}]},{"viewId": "######","dateRanges": [{"startDate": "2014-11-01", "endDate": "2014-11-30"}],"metrics": [{"expression": "ga:transactionRevenue"},{"expression": "ga:transactions"},{"expression":"ga:transactions / ga:sessions"},{"expression":"ga:revenuePerTransaction"}]}]};
var googleToken={};


var requestReport = function(reportRequest,token){


    reportRequest = JSON.stringify(reportRequest);
    //console.log(reportRequest);

    var requestObject = {
        method:'POST',
        hostname:'analyticsreporting.googleapis.com',
        path:'/v4/reports:batchGet',
        headers:{
            Accept:'*/*',
            Authorization:'Bearer '+token.access_token,
            'Content-Type':'application/x-www-form-urlencoded'
        }
    };

    var callbackGoogle = function(response){
        console.log('\n-----------------------\n');
        console.log('Requesting Report : Google Analytics\nStatus Code: [', response.statusCode +': '+ response.statusMessage+']');
        console.log('-----------------------\n\n');

        var data = [];

        response.on('data',function(chunk){
            data.push(chunk);
        });
        response.on('end',function(){
            var buff = new Buffer(data.join('')).toString();

            console.log('////////////////////////// Success //////////////////////////\n')
            console.log(buff);

        });

        response.on('error',function(e){
            console.log(e);
        });
    };

    var req = https.request(requestObject,callbackGoogle);
    req.on('error',function(e){
            console.log('requestReport Error:\n',e);
        });
    req.write(reportRequest);
    req.end();

};

(function googleAccess(){
    jwtClient.authorize(function(err,tokens){
        console.log('\n-----------------------\n');
        console.log('Authenticate: Google \n');

        if(err){
            console.log('Google Error',err);
            return;
        }

        googleToken = tokens;

        requestReport(googleTemplates,tokens);

        console.log('Success: true');
        console.log('\n-----------------------\n\n');
    })
})();

The console output is as follows:

-----------------------

Authenticate: Google 

Success: true

-----------------------

-----------------------

Requesting Report : Google Analytics
Status Code: [ 200: OK]
-----------------------

////////////////////////// Success //////////////////////////

{}

Does anyone have a suggestion as to why the payload is returning as an empty object? It should be a report JSON file.

回答1:

I found the issue! File this one under 'not seeing the forest for the trees'.

The requestObject should have 'Content-type':'application/json'.