首页 > 解决方案 > 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 但它对我不起作用(老实说,我也不确定我是否正确使用它)。

标签: javascriptmysqlsqlnode.jsexpress

解决方案


每个 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);
      //});
    });
});

推荐阅读