Google Analytics Reporting API返回空对象 - NodeJs

时间:2016-06-17 18:57:16

标签: json node.js google-analytics google-analytics-api google-api-nodejs-client

第一个问题,请耐心等待。

我正在使用NodeJS查询Google Analytics Reporting API。我能够收到我需要的OAuth 2令牌,当我查询API时,我得到了200响应。但是,返回的有效内容是一个空对象,而不是作为预期目标的JSON格式的报告响应。

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

控制台输出如下:

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

Authenticate: Google 

Success: true

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

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

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

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

{}

有没有人建议有效负载为什么作为空对象返回?它应该是一个报告JSON文件。

1 个答案:

答案 0 :(得分:0)

我发现了这个问题!在“没有看到树木的森林”下提交这个。

requestObject应该有'Content-type':'application/json'