Node.js GET请求处理器报错:读取bandInfo.id时变量未定义
问题:为何console.log(bandInfo)能输出,但读取bandInfo.id时提示变量未定义?
相关代码:
GET请求处理器代码
app.get("/:band", async (req, res) => { const page = req.params.band; try { const result = await db.query("SELECT * FROM artists"); const artistData = result.rows; const band = artistData.findIndex((info) => info.onewordid === page); const bandInfo = artistData[band]; console.log(bandInfo); const articlesresult = await db.query("SELECT * FROM articles WHERE artist_id = $1", [bandInfo.id]); res.render("artistpage.ejs", { artistinfo: bandInfo, data: artistData, articles: articlesresult.rows, }); } catch(err){ console.log(err) } });
示例band对象
{ id: 1, name: 'The Rolling Stones', picadress: 'backgroundpic2.jpeg', onewordid: 'stones' }
错误输出信息
undefined TypeError: Cannot read properties of undefined (reading 'id') at file:///Users/admin/Downloads/Web%20development%20Project/Backend/Blog%20Project%20Styling/index.js:83:15 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
原因分析与解决方案
原因
你看到的console.log(bandInfo)输出的就是undefined,这是因为findIndex方法在数组中找不到符合info.onewordid === page条件的元素时,会返回-1。而数组索引从0开始,artistData[-1]必然是undefined,此时读取bandInfo.id自然会触发“无法读取undefined的id属性”的错误。
这种情况仅在用户请求的:band参数(比如URL中的/unknown-band)不存在于数据库的onewordid字段值中时出现。
解决方案
在使用bandInfo之前先做存在性校验,避免读取undefined的属性:
方案1:优化findIndex的使用逻辑
app.get("/:band", async (req, res) => { const page = req.params.band; try { const result = await db.query("SELECT * FROM artists"); const artistData = result.rows; const bandIndex = artistData.findIndex((info) => info.onewordid === page); // 先判断是否找到匹配项 if (bandIndex === -1) { return res.status(404).send("该艺术家不存在"); } const bandInfo = artistData[bandIndex]; console.log(bandInfo); const articlesresult = await db.query("SELECT * FROM articles WHERE artist_id = $1", [bandInfo.id]); res.render("artistpage.ejs", { artistinfo: bandInfo, data: artistData, articles: articlesresult.rows, }); } catch(err){ console.log(err) } });
方案2:改用find方法更直观
find方法直接返回匹配的对象,找不到则返回undefined,可省去索引判断的步骤:
app.get("/:band", async (req, res) => { const page = req.params.band; try { const result = await db.query("SELECT * FROM artists"); const artistData = result.rows; // 直接找匹配的对象 const bandInfo = artistData.find((info) => info.onewordid === page); // 判断对象是否存在 if (!bandInfo) { return res.status(404).send("该艺术家不存在"); } console.log(bandInfo); const articlesresult = await db.query("SELECT * FROM articles WHERE artist_id = $1", [bandInfo.id]); res.render("artistpage.ejs", { artistinfo: bandInfo, data: artistData, articles: articlesresult.rows, }); } catch(err){ console.log(err) } });
内容的提问来源于stack exchange,提问作者user23771495
相关产品推荐
相关产品推荐

