node.jsmongodbexpressmongoosemean-stack

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


i'm trying on my API to set follow and unfollow function like social medias.

here is my user.controller.js follow function :

 module.exports.follow = async (req, res) => {
 if (!ObjectId.isValid(req.params.id))
 return res.status(400).send('ID unknown :' + req.params.id)

 try {
 // add to the friends list
 await User.findByIdAndUpdate(
  req.params.id,
  { $addToSet: { following: req.body.idToFollow } },
  { $push: { following: req.body.followerId } },
  (err, docs) => {
    if (!err) res.status(201).json(docs);
    else return res.status(400).jsos(err);
  }
 );
// add to friend list
 await User.findByIdAndUpdate(
  req.body.idToFollow,
  { $addToSet: { followers: req.params.id}},
  { new: true, upsert: true },
  (err, docs) => {
    // if (!err) res.status(201).json(docs);
    if (err) return res.status(400).jsos(err);
  }
)

}catch (err) {
  return res.status(500).json({ message: err });
}
};

When i try to "idToFollow" by entering real Id in my mongoDB i have this error :

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

I know this error come from my errors calls, but i don't know how to update my code. All my tries ends to broke.

Ps* I'm new in MEAN stack world :)


Solution

  • You are mixing callbacks and Promises. Your await does not have any effect, since mongoose is using the callback function and therefore does not return a Promise. You should simply remove the callback function and handle your code in a "synchronous" way by using await:

    module.exports.follow = async (req, res) => {
      if (!ObjectId.isValid(req.params.id))
        return res.status(400).send('ID unknown :' + req.params.id)
    
      try {
        // add to the friends list
        await User.findByIdAndUpdate(
          req.params.id,
          { $addToSet: { following: req.body.idToFollow } },
          { $push: { following: req.body.followerId } }
        );
    
        // add to friend list
        await User.findByIdAndUpdate(
          req.body.idToFollow,
          { $addToSet: { followers: req.params.id}},
          { new: true, upsert: true },
        )
        return res.status(201).json(docs);
    
      } catch (err) {
        return res.status(500).json({ message: err });
      }
    };
    

    Notes: