簡體   English   中英

Express JS TypeError:無法讀取未定義的屬性(讀取“0”)SQL 查詢錯誤

[英]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);
      //});
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM