简体   繁体   English

如何从 Node.js 中的 Google Analytics 获取数据

[英]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.我想阅读我网站的 Google Analytics 数据并在管理面板中呈现。

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.如何解决这个问题并将分析数据渲染到 ejs 文件。

Its looks like you have something issue with Proccess.env, so make sure you are getting proper values on it.看起来您的 Proccess.env 有问题,因此请确保您获得了正确的值。

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资源: 如何在 Nodejs 中使用 Google Analytics 报告 API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM