Error [ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client Error [ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client mongoose mongoose

Error [ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client


you need to return your error response once an error occurred or otherwise your function will keep running and executing the below code even after the error.

  '/add/grade',  [   check('name', 'grade name is require')  .not()  .isEmpty()],auth,admin,(req, res) => {const errors = validationResult(req);if (!errors.isEmpty()) return res.status(400).send({ errors: errors.array() });const grade = new Grade(req.body);grade.save((err, doc) => {  if (err) return res.status(400).send({ success: false, err });  return res.status(200).send({    success: true,    grade: doc,    msg: 'Grade add successfully'  });});});

because if an error occurs or any validation is failed the API sends the response but is not returned so the function keeps on going and executes all other code below it.

As you should know that in an HTTP request response can only be sent once and when the function again sends the response after an error it shows you that cannot send response headers after they are sent to the client.

Hope this helps. GOOD LUCK :)


You can send a response to the client only once when you send more than one time that will generate the error

[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to theclient

I was facing the same error. in my case, I was sending a response twice.1)before saving the user.

res.send(user);//<----after removing this statement my problem was fixed.

2)after saving the user

await user.save().then(result=>{       return res.send(result);            }).catch(err=>{        return res.sendStatus(500).send({            message:err.message|| "some error occured"        });            })