【问题标题】: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,但它对我不起作用(老实说,我也不确定我是否正确使用它)。

【问题讨论】:

  • 我猜这与异步无关,您收到此错误是因为您的 resultsundefined。你没有处理错误,所以不能保证你有正确的结果(或根本没有)
  • 是的,但我如何才能确保 INSERT 在 SELECT 之前发生?那么就没有可能的错误了,但我还是会做错误处理,以防万一...... :) THX!

标签: javascript mysql sql node.js express


【解决方案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);
      //});
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2021-11-03
    • 2021-11-08
    • 2021-12-31
    • 1970-01-01
    • 2022-07-09
    • 2022-08-07
    • 2022-01-11
    相关资源
    最近更新 更多