【发布时间】:2020-05-22 12:41:04
【问题描述】:
来自 node.js 应用程序(一个不和谐的机器人) 我尝试使用 npm 包 google-spreadsheet
访问 public googlesheet我仔细执行了每一步,但我只想使用 API 密钥 身份验证方法,而不是风险更大的 Oauth 身份验证
(我的 discord 机器人是公开的,在 heroku 上,即使我使用环境变量,我也不想处理太多敏感信息)
在 google-spreadsheet.js 的文档中提到:
// OR use API key -- only for read-only access to public sheets
doc.useApiKey('YOUR-API-KEY');
我可以成功连接到
spreadsheet
并阅读它的标题并获取每张纸的标题但是当我打电话时
await sheet.loadCells();
它给了我以下错误
Google API error - [401]
Request is missing required authentication credential.
Expected OAuth 2 access token,
login cookie or other valid authentication credential.
See https://developers.google.com/identity/sign-in/web/devconsole-project.
如果可能,仅使用 API KEY 身份验证的正确方法是什么或 READING ONLY 单元格?
这是我的完整代码:
const sheetId = "1Bny-ZsCG_oUuS0nTbR-7tBBZu47_ncS9qGYaMpuprWU"
var loaded = {}
if (message) {
message.reply("je me connecte à Google Sheets...")
}
const doc = new GoogleSpreadsheet(sheetId);
doc.useApiKey(process.env.GOOGLE_API_KEY);
await doc.loadInfo();
loaded.docTitle = doc.title;
loaded.sheets = {};
if (message) {
message.reply("...connection réussie, je récupère les infos...")
}
// get the spreadsheets
for (let s = 0; s < doc.sheetCount; ++s ) {
const sheet = doc.sheetsByIndex[s];
loaded.sheets[sheet.title] = {sheetReference:sheet};
loaded.sheets[sheet.title].data = []
await sheet.loadCells(); // <---------it seems to block here
for (let row= 0; row < sheet.rowCount; ++row) {
loaded.sheets[sheet.title].data.push([])
for (let col = 0; col < sheet.columnCount; ++col) {
let cell = sheet.getCell(row, col).value;
loaded.sheets[sheet.title].data[row].push(cell)
}
}
非常感谢!
【问题讨论】:
-
您的应用程序是否已授权范围:googleapis.com/auth/spreadsheets.readonly ??在 this for authorization protocols 阅读 sheet-api
-
您可能还会发现Sheets-API quickstart 花费的 10 分钟值得您花时间
-
是的,在@Tanaike 的回答中,我意识到我使用了错误的库。但是使用 Oauth2 , google-spreadsheet.js 运行良好并且使用简单
标签: node.js authentication discord.js google-sheets-api