node.js - 为什么我使用 google-api-nodejs-client 对 Google Analytics 的 API 调用在生产中不起作用?

标签 node.js google-analytics google-cloud-platform google-analytics-firebase google-api-nodejs-client

我调用 Google Analytics Reporting API使用 google-api-nodejs-client显示博客内的访问次数。

该博客托管在 Google App Engine 标准环境中。

在开发中,我正在使用 Application Default Credentials 验证我的 API 调用。 .我从专门为分析目的创建的帐户服务下载了带有凭据的 JSON 文件,将文件设置为 Google_Application_Credentials 环境变量,一切正常。我能够从 Google Analytics 获取数据并将其显示在网站上。

但这在生产中不起作用。我想getClient()它没有在该环境中获得凭据。

需要注意的事项: 1)我没有上传下载的 JSON 文件以及来自服务帐户的凭据(我认为这样做会违反直觉且不安全,根据我在文档中的理解,GCP 能够自动处理使用 API 身份验证);


const {google} = require("googleapis");

async function main () {

    // This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
    // environment variables.
    const auth = await google.auth.getClient({
        // Scope of the analytics reporting,
        // with only reading access.
        scopes: 'https://www.googleapis.com/auth/analytics.readonly',
    });

    // Create the analytics reporting object
    const analyticsreporting = await google.analyticsreporting({
        version: 'v4',
        auth: auth,
    });

    // Fetch the analytics reporting
    const res = await analyticsreporting.reports.batchGet({...});
    return res.data;
}

我已经没有选择了。有人可以帮我弄这个吗?

最佳答案

这是默认范围和应用程序默认凭据的问题。默认情况下,如果您不创建新服务帐户,您将从 GCE 元数据服务获取“应用程序默认凭据”:
https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-nodejs

这些凭据通常只有 cloud-platform范围,并且范围集不能更改(截至今天)。要完成这项工作,您有几个选择。

  • 您可以创建一个新的服务帐户,下载服务帐户 key ,然后使用 keyFile getClient 中的属性(property)方法选项来引用 key 。如果你这样做,你传递给 getClient 的范围会受到尊重。
  • 您可以使用运行 GAE 应用程序的服务帐户可用的范围。我没有亲自尝试过,但理论上应该是可能的。

  • 祝你好运!

    关于node.js - 为什么我使用 google-api-nodejs-client 对 Google Analytics 的 API 调用在生产中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950428/

    相关文章:

    php - 在 PHP 或 Node.js 中读取编码错误的 JSON 文件

    google-cloud-platform - 对话流 : display "processing" message on intents triggered by followup events

    Android Analytics 正确的接收器定义

    通过 Airflow 创建的 Kubernetes pod 保持运行状态

    docker - 日志是否保存在Google Kubernetes上

    node.js - MongoDb findone() 结果返回 null

    javascript - 如何在 Node.js 的服务器端使用 Object.values()

    javascript - 为基于Vue店面的网上商店设置RSS Feed(Google购物)

    javascript - 使用 list v3 将谷歌分析添加到 chrome 扩展中

    java - 谷歌分析平均 session 持续时间为 00 :00:00