what am i missing ? using axios to perform a delete request , troubleshooting with req.params.id using mongodb as bakcend

Viewed 319

I am trying to execute a function which deletes a post from the local mongodb database . I Have tested the code with postman it is working but in the frontend i am using axios and the id is needed to be passed as a request parameter , but i am getting an error. My code is unable to pass the id parameter , but backend code looks ok.

xhr.js:166 DELETE http://localhost:3000/api/posts/?id=5da802aa8b54d7220f84110e 404 (Not Found)

axios.delete('/api/posts/',{params:{id:'xyz'}})

although i tested in postman by directy inserting the id (http://localhost:5000/api/posts/xyz_id) with delete request, and it worked.

/////backend

  delete(req, res, next){
     const postId = req.params.id;
     Post.findOneAndDelete({ _id:postId })
    .then(post => res.status(204).send(post))
    .catch(next);
 }

//////frontend

  const deletePost =()=>{
   axios
  .delete('/api/posts/', { params:{ id:'5da802aa8b54d7220f84110e'}})
  .then(res => console.log('deleted'))
  .catch('err', err => console.log(err));
  };
2 Answers

The second argument of the axios request is typically used to pass in a req.body. In your backend logic, you're trying to use data available in the req.params, which should be passed via the route path on the front-end. Try this instead:

const deletePost = () => {
   axios
  .delete(`/api/posts/${5da802aa8b54d7220f84110e}`) //you can swap the number with an actual variable
  .then(res => console.log('deleted'))
  .catch('err', err => console.log(err));
  };

This assumes your API route looks something like app.delete("/api/posts/:id")

Validate that you don't have to provide some Authorization in headers:

 const deletePost =()=>{
       axios
      .delete('/api/posts/:id', { params:{ id:'5da802aa8b54d7220f84110e'}})
      .then(res => console.log('deleted'))
      .catch('err', err => console.log(err));
      };
Related