Home > Enterprise >  Can't see where multiple call of res caused the error : Cannot set headers after they are sent
Can't see where multiple call of res caused the error : Cannot set headers after they are sent

Time:11-09

I'm following a tutorial in the net. It's a MERN project with mongo/mongoose. When I have implemented the update function in the controller the following error has occured :

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

I've seen the answers about similar issue where they say it's because there is 2 or multiple call of res (res.json(), res.send() etc..), but I don't see where must I change this in the following function :

module.exports.updateUser = async(req, res) => {
if (!ObjectID.isValid(req.params.id))
    return res.status(400).send("ID unknown : "   req.params.id);

try {
    await UserModel.findOneAndUpdate({
            _id: req.params.id
        }, {
            $set: {
                bio: req.body.bio
            }
        },
        (err, docs) => {
            if (!err)
                return res.send(docs);
            if (err)
                return res.status(500).send({ message: err });
        }
    )
} catch (err) {
    return res.status(500).json({ message: err });
}

};

CodePudding user response:

Could you please change code like this:

module.exports.updateUser = async(req, res) => {
  if (!ObjectID.isValid(req.params.id))
      return res.status(400).send("ID unknown : "   req.params.id);
  
  try {
      const result = await UserModel.findOneAndUpdate({
              _id: req.params.id
          }, {
              $set: {
                  bio: req.body.bio
              }
          });
      return res.send(result);
  } catch (err) {
      return res.status(500).json({ message: err });
  }
  };

CodePudding user response:

It may be that you've mixed up two different error handling patterns.

You don't need try/catch if you're using built in error handling of findOneAndUpdate()


await UserModel.findOneAndUpdate({
            _id: req.params.id
        }, {
            $set: {
                bio: req.body.bio
            }
        },
        (err, docs) => {
            if (!err)
                return res.send(docs);
            if (err)
                return res.status(500).send({ message: err });
        }
)

and if you are using try/catch, you don't need findOneAndUpdate's error handling:

try {
    await UserModel.findOneAndUpdate({
            _id: req.params.id
        }, {
            $set: {
                bio: req.body.bio
            }
        })
} catch (err) {
    return res.status(500).json({ message: err });
}
  • Related