Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query error
Posted
技术标签:
【中文标题】Express JS TypeError: Cannot read properties of undefined (reading \'0\') SQL query error【英文标题】:Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query errorExpress JS TypeError: Cannot read properties of undefined (reading '0') SQL query error 【发布时间】:2021-12-22 07:48:54 【问题描述】:我试图在我的数据库中插入一些东西,然后直接访问它,但由于节点是异步的,这在某种程度上无法按计划工作。但我知道必须有办法让这一切顺利进行。 这是我的代码:
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,但它对我不起作用(老实说,我也不确定我是否正确使用它)。
【问题讨论】:
我猜这与异步无关,您收到此错误是因为您的results
是 undefined
。你没有处理错误,所以不能保证你有正确的结果(或根本没有)
是的,但我如何才能确保 INSERT 在 SELECT 之前发生?那么就没有可能的错误了,但我还是会做错误处理,以防万一...... :) THX!
【参考方案1】:
每个 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);
//);
);
);
【讨论】:
以上是关于Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query error的主要内容,如果未能解决你的问题,请参考以下文章
Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query error
node_modules/express/lib/router/index.js:458 throw new TypeError('Router.use() requires a middleware
TypeError:无法读取未定义的属性“获取”(Node.js)