【问题标题】:Fetching spreadsheet data does not update on client when new values are inserted in spreadsheet在电子表格中插入新值时,在客户端上获取电子表格数据不会更新
【发布时间】:2020-05-11 17:06:08
【问题描述】:

我正在使用 google-spreadsheet npm 包和 express 从我的电子表格中检索所有行。 在我的客户端,我正在使用 fetch 并记录控制台中的所有行。

我正在使用带有姓名/姓氏的简单电子表格。 每当我尝试在我的电子表格的行中手动添加一些新名称时,我都必须重新启动我的服务器才能看到使用更改的行再次获取数据。 更改工作表后使用间隔再次调用 api 仍然不会更新客户端上的数据。

有没有一种方法可以在我每次手动更改工作表中的某些内容时自动更新获取的数据,而无需每次都重新启动服务器?

index.js:

const GoogleSpreadsheet = require('google-spreadsheet')
const creds = require('./credentials.json')
const express = require('express')
app = express()

app.use(express.static('public'));


app.listen(3000, console.log('listening at http://localhost:3000/'))
var doc = new GoogleSpreadsheet('my spreadsheet ID');

// Authenticate with the Google Spreadsheets API.
doc.useServiceAccountAuth(creds, function (err) {

  // Get all of the rows from the spreadsheet.
  doc.getRows(1,  (err, rows) => {
    console.log(rows);
    app.get('/sheet', (req,res) =>{res.send(rows)})
  });
});

html:

<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

<script >
async function FetchFromSheet()
    {
        const response= await fetch('/sheet')
        const data = await response.json()
        console.log(data)
    }

    setInterval(() => {
        FetchFromSheet()
    }, 10000);
    </script>

</html>```



【问题讨论】:

    标签: node.js express google-sheets-api


    【解决方案1】:

    google-spreadsheet npm 包可让您对 Google 表格进行 API 调用,以获取最新版本的电子表格数据。 API 调用是根据您的定义进行的,默认情况下,并不意味着跟踪工作表本身的更改。这就是为什么您的数据仅在您重新启动服务器时更新的原因,因为您只调用一次 API(在启动时)

    您正在寻找的是Google Sheets webhook,它可以在正在更改的工作表上向您指定的路线发送 POST 请求。您基本上可以将此 webhook 请求的收据用作“提示”来刷新您的 Google 表格数据。

    【讨论】:

    • 谢谢!我花了一段时间才弄清楚,但我设法让它工作。 webhooks 拯救了一天!
    • @SuRots 你能使用这个 webhook 吗?我正在努力解决它。文章中的版本似乎与 Google 电子表格上现在使用的版本有所不同。找不到发布 > 部署为 Web 应用选项
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多