Stack Exchange
Error [ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (C:\root\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\root\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\root\node_modules\express\lib\response.js:267:15)
    at ServerResponse.send (C:\root\node_modules\express\lib\response.js:158:21)
    at grade.save (C:\root\route\api\listsData.js:223:32)
    at C:\root\node_modules\mongoose\lib\model.js:4604:16
    at C:\root\node_modules\mongoose\lib\utils.js:268:11
    at $__save.error (C:\root\node_modules\mongoose\lib\model.js:472:16)
    at C:\root\node_modules\kareem\index.js:246:48
    at next (C:\root\node_modules\kareem\index.js:167:27)
    at next (C:\root\node_modules\kareem\index.js:169:9)
    at Kareem.execPost (C:\root\node_modules\kareem\index.js:217:3)
    at _handleWrapError (C:\root\node_modules\kareem\index.js:245:21)
    at C:\root\node_modules\kareem\index.js:272:14
    at _next (C:\root\node_modules\kareem\index.js:94:14)
Emitted 'error' event at:

Please help, I was facing with this issue almost 3 days now, below is my backend nodejs code:
GradeModel
const mongoose = require('mongoose');

const GradeSchema = new mongoose.Schema({
  name: {
    type: String,
    maxlength: 100,
    required: true,
    unique: true
  }
})

module.exports = Grade = mongoose.model('Grade', GradeSchema);

AddGradeRoute
  '/add/grade',
  [
    check('name', 'grade name is require')
      .not()
      .isEmpty()
  ],
  auth,
  admin,
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) res.status(400).send({ errors: errors.array() });

    const grade = new Grade(req.body);

    grade.save((err, doc) => {
      if (err) res.status(400).send({ success: false, err });
      return res.status(200).send({
        success: true,
        grade: doc,
        msg: 'Grade add successfully'
      });
    });
  }
);

The issue is when I tried to add grade with the post request it's working fine, but if I put blank field and send the request again, app is crashed and it returns with the error above 'Cannot set headers after they are sent to the client'. Thank you.

You cannot send the headers once the response is sent to client. So, send the response only once when all the callbacks are executed. That should work.

To elaborate on Raja's comment, you have multiple res.status().send in your code that executes one after another in certain error situation. Make sure you return after each res.status().send event to ensure only one of them gets executed.

Yes, thank you for your opinion, it helped me a lot. I appreciate that.

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 :)

Yes, thank you for your opinion, I will tried to check it once again. I appreciate that.

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 the
client

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"
        });
        
    })

