错误[ERR_HTTP_HEADERS_SENT]:发送标头后无法设置标头到客户端位于ServerResponse.setHeader(_http_outgoing.js:485:11(在ServerResponse.header(E:\download\react native\chat app\backend\node_modules\express\lib\response.js:771:10(在ServerResponse.send(E:\download\react native\chat app\backend\node_modules\express\lib\response.js:170:12(在ServerResponse.json(E:\download\react native\chat app\backend\node_modules\express\lib\response.js:267:15(在E:\download\react native\chat app\backend\routes\routes.js:183:40在processTicksAndRejections(internal/process/task_queues.js:93:5({代码:'ERR_HTTP_HEADERS_SENT'}
代码:
app.post("/images", (req, res) => {
const uname = req.body.userName;
FreindRequest.find({ $and: [{ acceptance: "accept" }, { $or: [{ reciever: uname }, { sender: uname }] }] }).then(
users => {
if (users) {
users.map(user => {
ImageModel.find({ $or: [{ userName: user.sender }, { userName: user.reciever }] }).then(user => {
if (user) {
res.json(user);
}
else {
res.json({ error: "error" })
}
}).catch(err => console.log(err));
})
}
else {
res.json({ error: "error" });
}
}
).catch(err => res.json({ error: "error" }));
});
一个请求只能发送一个响应。所以您不应该在map函数中使用res.json((。
如果您想发送多个JSON。您可以在函数内创建一个数组,然后推送所有数据,并在映射函数后发送res.json((,如下所示。
app.post("/images",async (req,res)=>{
const uname=req.body.userName;
FreindRequest.find({$and:[{acceptance:"accept"},{$or:[{reciever:uname},{sender:uname}]}]})
.then( users=>{
if(users){
let userImages = []
await users.map(user=>{
ImageModel.find({$or:[{userName:user.sender},{userName:user.reciever}]})
.then(user=>{
if(user){
userImages.push(user)
} else {
res.json({error:"error"})
}
})
.catch(err=>res.json({error:"error"}));
})
res.json(userImages)
} else {
res.json({error:"error"});
}
})
.catch(err=>res.json({error:"error"}));
});