Skip to main content
 首页 » 编程设计

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

2025年05月04日104yjmyzz

我调用 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 应用程序的服务帐户可用的范围。我没有亲自尝试过,但理论上应该是可能的。

  • 祝你好运!