Google Analytics Reporting API返回空对象-NodeJs [英] Google Analytics Reporting API returning empty object - NodeJs

查看:114
本文介绍了Google Analytics Reporting API返回空对象-NodeJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

first question so bear with me.

我正在使用NodeJS查询Google Analytics(分析)Reporting API.我能够收到所需的OAuth 2令牌,并且在查询API时会收到200响应.但是,返回的有效负载是一个空对象,而不是预期目标的JSON格式的报告响应.

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

控制台输出如下:

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

Authenticate: Google 

Success: true

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

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

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

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

{}

有人对有效负载为何返回为空对象有任何建议吗? 应该应该是报告JSON文件.

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

推荐答案

我发现了问题!将其归档在看不见树木的森林"下.

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

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

这篇关于Google Analytics Reporting API返回空对象-NodeJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆