嗨,我想顯示從資料庫中帶入 ejs/html 頁面的陣列中的資訊,但出現“未定義”錯誤...
我收到錯誤/單擊查看圖片
然后我有一個 POST 方法在控制臺中顯示陣列中的所有內容,例如:
app.post('/quotes', (req, res) => {
datacollection.insertOne(req.body)
.then(result => {
console.log(result)
res.redirect('/quotes')
db.collection('datacollection').find().toArray()
.then(results => {
console.log(results)
})
.catch(error => console.error(error))
// ...
})
.catch(error => console.error(error))
});
在 html/ejs 頁面上,我有一個包含:
'<%= datacollection %>'
我正在嘗試通過以下方式傳遞值:
app.get('/quotes', (req, res) => {
db.collection('datacollection').find().toArray()
.then(results => {
res.render('quotes.ejs', { datacollection: results })
})
.catch(/* ... */)
})
我如何使它作業?
uj5u.com熱心網友回復:
您好,首先在您的獲取請求中您應該輸入
res.render("quotes")
代替
res.render("quotes.ejs")
這是錯誤的。
我假設在你的代碼中你有公共目錄和視圖目錄,為了正常作業并且你的代碼能夠看到它們。當你在像 mongo 這樣的資料庫中作業時,你必須保存新結果,然后重定向到路線
result.save();
res.redirect("/");
在獲取請求中試試這個
*your_db_model*.find({"result": {$ne: null}}, function(err, results){
if (results) {
res.render("quotes", {datacollection: results});
}
你也有陣列,所以你必須像這樣在 quote.ejs 中列印它
<% datacollection.forEach(function(data){ %>
<h1><%=data.title%></h1>
<% } %>
我希望這將幫助您找到代碼中的一些錯誤。如果您的代碼仍然無法正常作業,請再次發送。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514755.html
上一篇:如何創建雙向鏈表添加方法?
