【问题标题】:google-spreadsheet.js (npm) read only access to cell not working with API KEY - need OAuth?google-spreadsheet.js (npm) 只读访问不使用 API KEY 的单元格 - 需要 OAuth?
【发布时间】: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)
      }
    }

非常感谢!

【问题讨论】:

标签: node.js authentication discord.js google-sheets-api


【解决方案1】:

google-spreadsheet 的作者在这里。

我刚刚发布了一个可以解决这个问题的更新。这是我错过的谷歌 API 文档的一个非常微妙的差异。如果仅使用 API 密钥,loadCells 方法现在将默认为常规 get endpoint。 loadCells 的接口是一样的,但是在这种模式下只支持 A1 范围。

干杯!

【讨论】:

    【解决方案2】:
    • 您希望使用 API 密钥从 Google 电子表格中检索值。
    • Google 电子表格是公开共享的。
    • 您想使用google-spreadsheet 实现此目的。

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

    问题和解决方法:

    当我看到 google-spreadsheet 的 the source script 时,似乎 sheet.loadCells() 使用 API 密钥通过 POST 方法请求。 Ref 很遗憾,API 密钥不能使用 POST 方法。所以出现了这样的错误。我认为这个问题的原因是由于这个。例如,当使用来自 OAuth2 和服务帐户的访问令牌时,我可以确认 sheet.loadCells() 有效。从这种情况来看,这可能是一个错误或库的规范。

    幸运的是,可以使用 API 密钥从公开共享的 Google 电子表格中检索这些值。因此,作为几种解决方法之一,在这个答案中,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));
        }
      );
    });
    
    • 当您运行脚本时,将检索公共共享电子表格中所有工作表中的所有值。
    • 在上面的示例脚本中,使用了电子表格.get 和电子表格.values.batchGet 两种方法。

    参考资料:

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

    【讨论】:

    • 你肯定明白我的问题!谢谢,我只是快速搜索了一下,没有找到官方googleapis库。
    • 现在我终于使用 Oauth2 身份验证使其工作,但我肯定会尝试您的解决方案,因为我更喜欢只有 API KEY 存储在配置变量中。谢谢!
    • @Gui3 官方 googleapis 客户端herefirst link。希望对您有所帮助。
    • @Gui3 感谢您的回复。很高兴您的问题得到解决。
    • @Aerials 感谢您的支持。
    猜你喜欢
    • 2014-02-12
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 2015-11-11
    • 2018-07-16
    相关资源
    最近更新 更多