NodeJs google analytics reporting API returning null response object

Just getting started with a question.

In my project, I am utilizing NodeJS to interact with the Google Analytics Reporting API. I have successfully obtained the necessary OAuth 2 token and even receive a 200 response when querying the API. However, instead of receiving the expected JSON formatted report response, I am getting back an empty object as the payload.

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);
    
    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 output on the console looks like this:

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

Authenticate: Google 

Success: true

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

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

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

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

{}

I'm puzzled as to why I'm only getting an empty object as the payload instead of the expected JSON report file. Any ideas on what might be causing this issue?

Answer №1

Hooray, I've finally located the problem! Let's categorize this as a classic case of 'cannot see the big picture due to focusing on small details'.

The requestObject must include

'Content-type':'application/json'
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to run "npm init" before installing packages with npm, or can I do it afterwards too?

While I understand that I can still run the node.js app without using npm init and going straight to installation, it is considered a good practice. However, if I happen to forget to run npm init initially, what steps can I take to enhance my application? ...

Convert the rails database to a JSON file

Is there a way to export the information stored in a Rails sqlite3 database to a file? Currently, I am working with rails 4. My goal is to extract all of the data from my database for future use when resetting it or transitioning to a different database ...

Learn how to create horizontal scrolling cards using React and Material-UI!

I am working on developing a react component that will showcase 3 cards, each displaying content from an array in a horizontal layout. The goal is to have left and right buttons that allow users to scroll through additional sets of 3 cards until the entire ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Creating a custom shortcut in the shell to quickly switch between directories

In my workflow, I incorporate bower and grunt to manage my project dependencies. To streamline the installation process, I decided to set up bower alongside grunt and automatically fetch all necessary bower components. This involved creating a package.json ...

Tips for fixing the issue: TypeError: app.listen is not a valid method

I have recently started learning about node.js and was working on my very first project. However, I encountered an error stating "TypeError: app.listen is not a function" when trying to start the app. Can someone please guide me on how to resolve this issu ...

I encountered issues with my Bower calls being blocked by the corporate proxy, which resulted in errors when attempting to update my

When attempting to install bower through npm for the angular seed project setup, I encountered errors due to my corporate proxy causing issues. retry Request to https://bower.herokuapp.com/packages/angular failed with ECONNRESET, retrying in 1.2s bower ...

Utilizing varying class types from input data

I have a collection of JSON files where I define different types of objects. Each object includes its type as a field, and I want to load the file and instantiate a new class for each JSON object based on its type, passing the remaining JSON data to the co ...

As I tried running both `npm install --force` and `npm i`, an unexpected error occurred

npm WARN using --force Recommended protections disabled. npm WARN ERESOLVE overriding peer dependency npm WARN While resolving: @material-ui/[email protected] npm WARN Found: [email protected] npm WARN node_modules/react npm WARN react@"^18.2.0" fro ...

Best method for retrieving JSON information from the internet using an API

Looking to work with a URL like this: http://site.com/source.json?s= My goal is to develop a Python class that can take in the "s" query, send it to the specified site, and then extract the JSON results. I've made attempts at importing json and set ...

I keep encountering the error message "$(".dropdown-toggle").dropdown is not a function" while attempting to use Dropdowns with Jade and Bootstrap

I am attempting to implement a Bootstrap dropdown in my Jade layout. However, I keep encountering an error when trying to run $(".dropdown-toggle").dropdown in my Jade file: $ is undefined $(".dropdown-toggle").dropdown is not a function What could be ...

Load JSON file in ExtJs using Ext.Ajax.request method: A step-by-step guide

I am exploring a new approach to loading a json file in ExtJs. In the past, I used jQuery to achieve this functionality as shown in the code snippet below: Ext.define('app.store.Students', { extend: 'Ext.data.Store', model: &ap ...

Issue with the "npm start" command has occurred at the script start for [email protected] npm ERR! react-scripts cannot be located

As I work on developing a basic tic tac toe game in React, my process begins by creating the app using the following commands: npx create-react-app my-app cd my-app npm start Initially, everything runs smoothly. However, upon installing some ...

What could be causing my Node.js function to return undefined?

function findUserByStudentId(NIM) { db.query('SELECT * FROM data_admin WHERE id_mahasiswa = ?', [NIM], async (err, result) => { if (!result) { return null } else { var userData = await { ...

JavaScript: Converting an Array to a String

Having trouble making the string method work with an array - it keeps showing up as empty. let url = "https://api.myjson.com/bins/be7fc" let data =[]; fetch(url) .then(response => response.json()) .then(result => data.push(r ...

Using Node.js, iterate over every key-value pair within a Redis hash data structure

I am currently navigating my way through the world of redis and node, attempting to iterate over some test hash keys that I have generated. My goal is to display the results on the screen. The expected output should look like this: { "aaData": [['Tim ...

Guide to passing JSON Data as a response in Vue.js version 2

Currently working on a Vue.js website that interacts with an API (route -> /api/**). However, I am struggling to figure out the process of sending JSON responses. Is there a similar method like res.json() in Vue.js as express.js has? ...

Unraveling JSON data within PHP after it has been passedbindParam

Decoding JSON Data with PHP I have a variable named jsonvar containing {"rating":"good"} After using the $.ajax code to send it to my PHP file (jsonproc.php), I'm unsure of how the PHP script should be structured. $.ajax({ url: &apo ...

Steps to set up React on Command Prompt through npm

When installing create-react-app globally using npm, you may encounter warnings and issues that require your attention. For example, the version of tar being used is deprecated and no longer supported, with potential security vulnerabilit ...