从node.js应用程序(不和谐的bot)
我尝试使用npm软件包google-spreadsheet访问公开的Googlesheet

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

(我的discord bot是公开的,在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身份验证,什么是正确的方式或仅读取单元格?

这是我的完整代码:

  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 Spreadsheet检索值。
Google电子表格是公开共享的。
您想使用google-spreadsheet实现。


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

问题和解决方法:

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

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

示例脚本:

首先,请安装googleapis。并设置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));
    }
  );
});



运行脚本时,将从公共共享的电子表格中的所有工作表中检索所有值。
在上面的示例脚本中,使用了两种方法sheetssheets.get和sheetssheets.values.batchGet。


参考文献:


google-api-nodejs-client
Method: spreadsheets.get
Method: spreadsheets.values.batchGet


如果我误解了您的问题,而这不是您想要的方向,我深表歉意。

关于node.js - google-spreadsheet.js(npm)对不使用API​​ KEY的单元的只读访问权限-是否需要OAuth?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60095462/

10-16 21:25