是否可以在同一个Ejs页面上显示集合(mongoDb)和所有集合中的每个元素



我正试图用nodeJs/Express/MongoDb/Ejs(用于Html渲染(为我的网站创建一个小论坛当我试图展示收藏的内容时,我有一个绝妙的:";在它们被发送到客户端之后不能设置报头";我不明白。。即将在我的网站上创建一个论坛,就像所有的收藏都是用户发送的问题一样,每个收藏中都有用户的评论和回复。。

这是我的代码,底部是有问题的部分。。没有这一切工作。。祝晚上愉快

app.get("/vosQuestions",(req,res)=>{    
let test = db.collection(test1.toString())
const curseur = db.listCollections().toArray()    
.then (result=>{ 
res.setHeader("Content-Type", "text/html")
res.render("vosQuestions",{collectionName :result })
res.end()
})
.catch(error=>console.error(error))
// Problem part //
test.find(function(err,results){
if (err) throw err
console.log("le find est :"+results)       
res.render("vosQuestions",{TEST :results })
res.end()
})
})

您收到错误:can not set headers after they are sent to the client,因为您试图在发送一次响应后再次将其发送回客户端。

您需要先获取所有必需的集合或文档,然后只将响应发送回客户端。您只能发回一个响应。

试试这个:

app.get("/vosQuestions",async (req,res)=>{    
try{
let test = db.collection(test1.toString())
let  collectionName = await db.listCollections().toArray()   
let tests = await test.find();
res.setHeader("Content-Type", "text/html")
res.render("vosQuestions",{collectionName: collectionName, TEST :tests })
res.end()
}
catch(error){
console.error(error)
//send the error response back here.
}
})

注意:为了更好的可读性,我在这里使用了async/await。

最新更新