node.js - 使用服务帐户进行 Google Sheets Api 授权
问题描述
我正在使用googleapis库 v44.0.0。当我尝试登录时,出现错误。
Google Sheets API 之前未在项目 33120758 中使用或已禁用。通过访问https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=33120758启用它,然后重试。如果您最近启用了此 API,请等待几分钟让该操作传播到我们的系统并重试。
我在同一个项目上使用 google-auth-library 版本 ^ 0.10.0。而这个错误不是。
const { google } = require("googleapis");
// ...
const JwtClient = new google.auth.JWT(
client_email,
null,
private_key,
["https://www.googleapis.com/auth/spreadsheets"]
);
await JwtClient.authorize();
google.options({ auth: JwtClient });
// ...
const client = google.sheets({ version: "v4" });
const data = await client.spreadsheets.get({ spreadsheetId: myId});
解决方案
- 您想将 Sheets API 与服务帐户一起使用。
- 您想使用 googleapis 和 Node.js 来实现这一点。
如果我的理解是正确的,那么这个修改呢?
修改后的脚本:
从:await JwtClient.authorize();
google.options({ auth: JwtClient });
// ...
const client = google.sheets({ version: "v4" });
const data = await client.spreadsheets.get({ spreadsheetId: myId});
至:
const client = google.sheets({ version: "v4", "auth": JwtClient });
const data = await client.spreadsheets.get({ spreadsheetId: myId});
console.log(data.data)
笔记:
- 如果您想从您自己的 Google Drive 上的电子表格中检索数据,请与服务帐户的电子邮件共享电子表格。这样,可以从服务帐户中检索电子表格。请注意这一点。
在我的环境中,我可以确认修改后的脚本有效。但如果这不能解决您的问题,我深表歉意。
推荐阅读
- c# - 统一实例化函数不会在所需位置生成对象
- r - 有没有办法在美元符号之前加上负号
- mysql - oracle数据库内两列之间的数学运算(描述所需的结果)
- python - 游戏角色没有正确受到伤害 - python 3.6
- firebase - SwiftUI:.onappear 未在第一个选项卡中显示来自 firebase 的数据
- scala - 我的 fs2 scala 程序没有按预期执行
- c - 在 Docker Alpine 中编译 NSS 模块 - 致命错误:nss.h:没有这样的文件或目录
- r - 如何在 R 中的公式中写使用 quos?
- python - 设置数据集的随机种子以始终选择相同的图像/皮尔逊相关性
- markdown - 向 MARP 演示文稿添加内部链接