谷歌电子表格.js (npm) 对无法使用 API KEY 的单元格进行只读访问 - 需要 OAuth?



来自节点.js应用程序(不和谐机器人( 我尝试使用 npm 包访问公共谷歌工作表谷歌电子表格

我仔细遵循了每个步骤,但我只想使用 API 密钥身份验证方法,而不是风险更大的Oauth标识

(我的 Discord 机器人是公开的,在 Heroku 上,即使我使用环境变量,我也不想弄乱太多敏感信息(

谷歌电子表格的文档中.js它提到:

// OR use API key -- only for read-only access to public sheets
doc.useApiKey('YOUR-API-KEY');

我成功地可以连接到 电子表格阅读它的标题并获取每张纸的标题,但是当我打电话时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 密钥身份验证的正确方法或只读单元格是什么?

这是我的完整代码:

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)
}
}

谢谢!

  • 您想使用 API 密钥从 Google 电子表格中检索这些值。
  • Google 电子表格是公开共享的。
  • 你想使用谷歌电子表格来实现这一点。

如果我的理解是正确的,那么这个答案呢?请将此视为几种可能的答案之一。

问题和解决方法:

当我看到谷歌电子表格的源脚本时,似乎使用 API 密钥使用 POST 方法sheet.loadCells()请求。引用 不幸的是,API 密钥不能使用 POST 方法。所以发生了这样的错误。我认为这个问题的原因是由于这个。例如,当使用来自 OAuth2 和服务帐户的访问令牌时,我可以确认sheet.loadCells()有效。在这种情况下,这可能是错误或库的规范。

幸运的是,可以使用API密钥从公开共享的Google电子表格中检索这些值。因此,作为几种解决方法之一,在此答案中,用于Node.js的googleapis被用作一种简单的方法。这是官方图书馆。

示例脚本:

首先,请安装谷歌APIS。并请设置spreadsheetIdAPIKey的变量。

const { google } = require("googleapis");
const spreadsheetId = "1Bny-ZsCG_oUuS0nTbR-7tBBZu47_ncS9qGYaMpuprWU"; // This is from your script.
const APIKey = "### your API key ###";
const sheets = google.sheets({version: "v4", auth: APIKey});
sheets.spreadsheets.get({ spreadsheetId: spreadsheetId }, (err, res) => {
if (err) {
console.error(err);
return;
}
sheets.spreadsheets.values.batchGet(
{
spreadsheetId: spreadsheetId,
ranges: res.data.sheets.map(e => e.properties.title)
},
(err, res) => {
if (err) {
console.error(err);
return;
}
console.log(JSON.stringify(res.data));
}
);
});
  • 运行脚本时,将检索公开共享电子表格中所有工作表中的所有值。
  • 在上面的示例脚本中,使用了 spreadsheets.get 和 spreadsheets.values.batchGet 的 2 种方法。

引用:

  • google-api-nodejs-client
  • 方法:电子表格.get
  • 方法:电子表格.值.批处理获取

如果我误解了你的问题,这不是你想要的方向,我很抱歉。

谷歌电子表格的作者。

我刚刚发布了一个应该可以解决此问题的更新。这是我错过的谷歌API文档中一个非常微妙的差异。如果仅使用 API 密钥,loadCells方法现在将默认为常规 get 终结点。称重传感器的接口相同,但在此模式下仅支持 A1 范围。

干杯!

最新更新