Javascript 是否可以在同一Ejs页面上显示集合(mongoDb)和所有集合中的每个元素?
我正试图用nodeJs/Express/MongoDb/Ejs(用于Html呈现)为我的网站创建一个小论坛 当我试图显示收藏的内容时,我有一个惊人的想法:“在它们发送到客户机后不能设置标题”,我不明白。。即将在我的网站上创建一个论坛,所有的收藏都是用户发送的问题,每个收藏中都有用户的评论和回复 这是我的代码,底部是有问题的部分。。如果没有这些,所有的工作。。 祝你晚上愉快Javascript 是否可以在同一Ejs页面上显示集合(mongoDb)和所有集合中的每个元素?,javascript,node.js,mongodb,express,ejs,Javascript,Node.js,Mongodb,Express,Ejs,我正试图用nodeJs/Express/MongoDb/Ejs(用于Html呈现)为我的网站创建一个小论坛 当我试图显示收藏的内容时,我有一个惊人的想法:“在它们发送到客户机后不能设置标题”,我不明白。。即将在我的网站上创建一个论坛,所有的收藏都是用户发送的问题,每个收藏中都有用户的评论和回复 这是我的代码,底部是有问题的部分。。如果没有这些,所有的工作。。 祝你晚上愉快 app.get("/vosQuestions",(req,res)=>{ let
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()
})
})
您收到错误:
发送到客户端后无法设置标题
,因为您正在尝试在发送一次响应后再次将其发送回客户端
您需要首先获取所有必需的集合或文档,然后只将响应发送回客户机。您只能返回一个响应
试试这个:
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/wait。您收到错误:
在发送到客户端后无法设置头文件
,因为您正在尝试在发送一次响应后再次将其发送回客户端
您需要首先获取所有必需的集合或文档,然后只将响应发送回客户机。您只能返回一个响应
试试这个:
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/Wait。对于此部分
“发送到客户端后无法设置标题”
您必须使用Return对于此部分“发送到客户端后无法设置标题”
您必须使用Return这很有效!非常感谢您抽出时间。祝您有个美好的一天!这就是工作!非常感谢您抽出时间。祝您有个美好的一天!