【发布时间】:2019-05-25 19:13:11
【问题描述】:
我使用google-api-nodejs-client 调用Google Analytics Reporting API 以显示博客内的访问次数。
此博客托管在 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;
}
我已经没有办法了。有人可以帮我解决这个问题吗?
【问题讨论】:
-
Google_Application_Credentials全部大写。 App Engine 身份:cloud.google.com/docs/authentication/… -
@JohnHanley,这不是问题所在。正如我所说,一切都在开发环境中运行良好。问题出在生产环境中,由 Google Cloud 自动配置和处理。
-
我想知道缺少什么部分。我已经完成了在文档中找到的所有内容。我唯一没有做的是使用API App Engine App Identity,因为他们还没有发布任何与 Node.js 相关的内容。
-
我有一个疑问。我是否需要将包含我的服务帐户密钥的 JSON 文件上传到生产环境并将其设置为
GOOGLE_APPLICATION_CREDENTIALS以在生产环境中验证我的 API 调用?还是仅在开发中需要? -
您可以选择使用 App Engine 的默认服务帐户进行身份验证,或者通过 Json 凭据文件手动指定服务帐户(您在开发中所做的方式)。
标签: node.js google-analytics google-cloud-platform google-analytics-firebase google-api-nodejs-client