简体   繁体   中英

How to get data from Google Analytics in Node.js

I want to read my website's Google Analytics data and render in admin panel.

Here is my codes:

const google = require('googleapis')
const scopes = 'https://www.googleapis.com/auth/analytics.readonly'
const jwt = new google.auth.JWT(process.env.GOOGLE_CLIENT_EMAIL, null, process.env.PRIVATE_KEY, scopes)
const view_id = '196847632'

async function getData() {
    const response = await jwt.authorize()
    const result = await google.analytics('v3').data.ga.get({
      'auth': jwt,
      'ids': 'ga:' + view_id,
      'start-date': '30daysAgo',
      'end-date': 'today',
      'metrics': 'ga:pageviews'
    })
}

But I'm getting this error:

const jwt = new google.auth.JWT(process.env.GOOGLE_CLIENT_EMAIL, null, process.env.PRIVATE_KEY, scopes)
TypeError: Cannot read property 'JWT' of undefined

How to solve this problem and get the Analtyics data to render to ejs file.

Its looks like you have something issue with Proccess.env, so make sure you are getting proper values on it.

If your private key is something like this:

-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkQ\nPmG+bRj7TkHwXJf2cx99CKW3usWKgn7EqFdFHOOQ1Z01+48SxHgTCJcd5sKy8Cf1iElXOXhIyTgnRiYm5FT1p2lMv8c71G\ngwB0kSFp5fu7vB7cGJXDMKU=\n-----END PRIVATE KEY-----\n

then try accessing it like:

const jwt = new google.auth.JWT( process.env.CLIENT_EMAIL, null, process.env.PRIVATE_KEY.replace(/\\n/g, "\n"), scopes );

Resource: How To Use Google Analytics Reporting API With Nodejs

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