while testing update post in my mern project it’s done fine the post will update but the page disappear and am facing this error and after i restart the server the updated post will be shown like the error never happened
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:405:5)
at ServerResponse.setHeader (node:_http_outgoing:648:11)
at ServerResponse.header (C:UsersهDesktopsocial-websitebackendnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (C:UsersهDesktopsocial-websitebackendnode_modulesexpresslibresponse.js:174:12)
at ServerResponse.json (C:UsersهDesktopsocial-websitebackendnode_modulesexpresslibresponse.js:278:15)
at updatePost (file:///C:/Users/%D9%87/Desktop/social-website/backend/controllers/postController.js:140:25)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: ‘ERR_HTTP_HEADERS_SENT’
}
this is my postController.js code:
const updatePost = async(req, res) => {
const postId = req.params.id;
try {
const post = await Post.findById(postId);
let { text, img } = req.body;
console.log(text)
if(!post) return res.status(400).json({ error: "Post Not found!" })
const user = await User.findById(req.user._id);
// if(!user) {
// return res.status(404).json({ error: "User not found!" })
// }
if(post.postedBy.toString() !== req.user._id.toString()){
return res.status(401).json({ error: "You cannot update other user's post" });
}
if(user._id.toString() !== req.user._id.toString()){
return res.status(401).json({ error: "Unauthorized to update post" })
}
const maxLength = 500;
if(text.length > maxLength){
return res.status(400).json({ error: `Text must be less than ${maxLength} characters!` })
}
console.log(post)
if(img){
if(post.img){
await cloudinary.uploader.destroy(post.img.split("/").pop().split(".")[0])
}
const uploadedResponse = await cloudinary.uploader.upload(img);
img = uploadedResponse.img;
}
const updatedPost = await Post.findByIdAndUpdate({_id: postId}, {text, img}, {new: true});
post.text = text || post.text
post.img = img || post.img
if( updatedPost ) res.status(200).json(updatedPost);
updatedPost = await post.save();
} catch (err) {
res.status(500).json({ error: err.message });
console.log(err)
}
};
2
Answers
It seems like the error is occurring because you are trying to send multiple responses to the client within your updatePost function. Specifically, it appears that you are sending a response (using res.json or res.status) after certain conditions are met, but then the code continues to execute and sends another response later in the function.
code :
code :
To resolve this issue, you should ensure that your function exits after sending a response. You can use return after sending a response to stop further execution of the function. Here’s a modified version of your code:
code :
This code includes return statements after sending responses, which should prevent the "Cannot set headers after they are sent to the client" error.
Looks like you just need to swap these two lines as
post.save
is throwing an error.