javascript - Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query error
问题描述
我试图在我的数据库中插入一些东西,然后直接访问它,但是因为节点是异步的,所以这在某种程度上无法按计划工作。但我知道必须有办法让这一切顺利进行。这是我的代码:
router.post('/anzeigeerstellen', upload_inserat.single('Anzeigebild'), function (req, res) {
let titel = req.body.TitelderAnzeige,
beschreibung = req.body.Beschreibung,
inbild = req.file.filename,
ses = req.session;
pool.query("INSERT INTO inserat (titel, beschreibung, inseratbildname, email)
VALUES (?, ?, ?, ?)",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => {
pool.query("SELECT iid FROM inserat WHERE titel = ?, beschreibung = ?,
inseratbildname = ?, email = ?",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => {
res.redirect('anzeige?id=' + results[0].iid);
});
});
});
错误如下:
TypeError: Cannot read properties of undefined (reading '0')
我已经尝试过 async 和 await 但它对我不起作用(老实说,我也不确定我是否正确使用它)。
解决方案
每个 SQL 查询都是一个承诺,这意味着当您插入或要求数据库为您获取(选择)数据时,服务器需要一些时间来执行您的查询。由于 NodeJs 具有同步特性,它会在您从数据库中获取结果之前执行下一行代码。因此,你得到了undefined
.
我不太了解该select
语句的目的,但如果您想知道id
插入行的 ,SQL 会将其作为result
.
因此,如果您希望异步使用 javascript,查询将如下所示:
//Setting the route asynchronous
router.post('/anzeigeerstellen', upload_inserat.single('Anzeigebild'), async (req, res)=> {
let titel = req.body.TitelderAnzeige,
beschreibung = req.body.Beschreibung,
inbild = req.file.filename,
ses = req.session;
//Awaiting until the db resolves
await pool.query("INSERT INTO inserat (titel, beschreibung, inseratbildname, email)
VALUES (?, ?, ?, ?)", [titel, beschreibung, inbild, ses.email],
(err, results, fields) => {
//Always check if there is an error
if (err) console.error(err)
else console.log(results) //results should be the id of the row or the row itself
/*pool.query("SELECT iid FROM inserat WHERE titel = ?, beschreibung = ?,
inseratbildname = ?, email = ?",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => { There is no need for this query since the results of the upper query is the row you wanted*/
res.redirect('anzeige?id=' + results[0].iid);
//});
});
});
推荐阅读
- java - 链接到另一段代码 - java - 初学者
- r - 如何获取 Flexdashboard 文档中的当前活动选项卡以响应式显示不同的 UI
- docker - 在openshift中限制未经授权的登录
- list - 如何使用嵌套的 for 循环创建随机列表
- angular - ArcGIS 4.16 Angular中内容的弹出模板自定义功能
- aerospike - 在 Ubuntu 20.04 上安装 aerospike 社区服务器
- xpages - 加载文档时 xpage 性能缓慢
- bots - ms 团队自定义应用程序与机器人开始聊天会话
- javascript - 如何将内容脚本变量发送到后台脚本?(Chrome 扩展程序)
- django - 尝试从 Django 博客中的标题帖子中删除 url