Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) at ServerResponse.header (E:\download\react-native\chat app\backend\node_modules\express\lib\response.js:771:10) at ServerResponse.send (E:\download\react-native\chat app\backend\node_modules\express\lib\response.js:170:12) at ServerResponse.json (E:\download\react-native\chat app\backend\node_modules\express\lib\response.js:267:15) at E:\download\react-native\chat app\backend\routes\Routes.js:183:40 at processTicksAndRejections (internal/process/task_queues.js:93:5) { code: 'ERR_HTTP_HEADERS_SENT' }
The code:
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" }));
});
find
query? If you do that how can you get the execution control back to execute the next user element? You are usingres.json()
so many places needlessly and that is what causing the problem. And why are you writing a post request to find the records, post request should save the data. I don't see anywhere in the code saving the data. – kavigun