我调用 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
范围,并且范围集不能更改(截至今天)。要完成这项工作,您有几个选择。
keyFile
getClient
中的属性(property)方法选项来引用 key 。如果你这样做,你传递给 getClient
的范围会受到尊重。 祝你好运!
关于node.js - 为什么我使用 google-api-nodejs-client 对 Google Analytics 的 API 调用在生产中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950428/