【发布时间】:2022-06-11 18:53:19
【问题描述】:
所以我正在构建一个 API 原型,并且我有从 Google 表格(作为 CMS)读取数据的代码,但问题是在调用我在 Express.js 中定义的路由时,它没有从床单。它适用于表 1,但不适用于表 2。 要读取我使用这个包的数据:https://www.npmjs.com/package/google-spreadsheet
Google 表格副本的链接:https://docs.google.com/spreadsheets/d/1yx0iRPPho2H1OGrvTAspkTr2b1zwzbkxeb7hRuqqNwc/edit?usp=sharing
相关代码:
router.get('/getallcontent', async function (req, res) {
const doc = new GoogleSpreadsheet('sheetId');
await doc.useServiceAccountAuth({
client_email: creds.client_email,
private_key: creds.private_key
});
const info = await doc.loadInfo();
const sheet = doc.sheetsByIndex[1];
const rows = await sheet.getRows()
// console.log(rows)
let contents = []
function Content(title, content, sku, author, lesson) {
this.title = title;
this.content = content;
this.sku = sku;
this.author = author;
this.lesson = lesson;
}
await rows.forEach(row => {
let content = new Content(
row._rawData[0],
row._rawData[1],
row._rawData[2],
row._rawData[3],
row._rawData[4]
)
contents.push(content)
})
res.json(Response.success(req, { content: contents }))
})
调用路由时的响应:
{"request":{"result":"success","message":""},"body":{"lessons":[]}}
预期响应:
{"request":{"result":"success","message":""},"body":{"content":[{"title": "Requesting Clearance","content": "some html markup text", "sku": "requesting-clearance", "author": "John D", "lesson": "test-lesson"}]}}
测试脚本确实有效:
async function getLessons() {
const doc = new GoogleSpreadsheet('1T8-rIN4w-T1OuYRuQ-JYI-15l9RqOXqDQ2KehWyp44E');
await doc.useServiceAccountAuth({
client_email: creds.client_email,
private_key: creds.private_key
});
const info = await doc.loadInfo();
const sheet = doc.sheetsByIndex[1];
const rows = await sheet.getRows()
rows.forEach(row => {
printContent(row)
})
}
async function printContent(rows) {
let lesson = {
title: rows._rawData[0],
content: rows._rawData[1],
sku: rows._rawData[2],
author: rows._rawData[3],
lesson: rows._rawData[4]
};
console.log(lesson)
}
【问题讨论】:
-
当我看到你的脚本时,我认为脚本会从第二张表中检索值。所以,关于
It works for sheet 1 but not for sheet 2.,我无法理解。为了正确理解您当前的问题,能否请教一下It works for sheet 1的contents的值?而且,您能否从第二张表中提供您预期的样本值contents? -
@Tanaike 抱歉应该解释得更好。我对工作表 1 使用了类似的功能,它按预期工作。所以表 1 是谷歌表本身副本中的课程表,表 2 是内容表。我现在将编辑帖子以添加预期的样本值
contents。谢谢! -
感谢您回复和更新您的问题。当我看到您更新的问题时,您的预期值为
"body":{"content":[{"title": "Requesting Clearance","content": "some html markup text", "sku": "requesting-clearance", "author": "John D", "lesson": "test-lesson"}]}。但是,您当前的值似乎是"body":{"lessons":[]}。当我看到你的脚本时,我找不到lessons的密钥。那么,我能问一下正确复制问题的详细流程吗? -
@Tanaike 就是这样,我不知道为什么会这样。我运行代码,去路线,它给了我。所以它应该做的流程是1.登录谷歌服务帐户以访问谷歌表,2.读取谷歌表的行,3.对于每一行它获取数据,使其成为一个对象并将其推送到包含所有数据的数组中, 4. 返回包含所有数据的数组以及默认的 API 响应。它在做什么,我不知道。
-
感谢您的回复。从您的回复来看,您的脚本只是您的展示脚本。并且,当您运行显示脚本时,将返回键为
lessons的值。我的理解正确吗?
标签: node.js express google-sheets google-sheets-api