Search code examples
mongodbmongooseaxios

my delete method of axios didn't work while post method work


I am making likes, dislikes function. everything is working fine, except this delete method 😐

at React :

const goDownLike = async () => {
  const variables = {
    fromWhom: user.userData._id,
    toWhat: toWhat
  };

  await axios.delete('/api/heart/downLike', variables);
}

at Node.js :

router.delete('/downLike', (req, res) => {
  Like.findOneAndDelete(req.body).exec((err, result) => {
    if (err) return res.status(400).json({ success: false, err });
    res.status(200).json({ success: true });
  });
});

when I clicked heart everytime, it seemed like it deleted somebody's likes including mine 😐

so I changed like this:

router.delete('/downLike', (req, res) => {
  const { fromWhom, toWhat } = req.body;
  Like.findOneAndDelete({ fromWhom: fromWhom, toWhat: toWhat }).exec(
    (err, result) => {
      if (err) return res.status(400).json({ success: false, err });
      res.status(200).json({ success: true });
    }
  );
});

but this is actually do not delete any likes, even mine!

I changed from this

Like.findOneAndDelete

to this

Like.deleteOne

and this is not working, too. it delete nothing.

so I changed delete method to post method and finally it worked. 😐 my likes was deleted and somebody's heart was not.

but I don't want to use post method instead of delete method 😐 I want to keep the rules of RESTful.

What should I do? What did I missed?

thanks for your helps.


Solution

  • The reason it works with POST and not DELETE is that the second parameter for axios.post() is the body, whereas the second parameter for axios.delete() is the axios config object. This is presumably because there has been some disagreement and change over time as to whether DELETE requests can or should have a body, and what should happen if they do.

    You can pass data in the config object, as seen here.