Noopur Porwal
Noopur Porwal

Reputation: 11

Axios delete giving 404 after deleting from database

I am sending a delete request using axios from my React frontend to node js express backend with mongo DB. Although the data does get deleted from my database but I still get an error 404 Not Found.

Here is React code

axios
    .delete(`http://localhost:8000/notes/${id}`)
    .then(res => {
      console.log("The response is "+res.data)
    })
    .catch(err => {
      console.log("There was an error "+ JSON.stringify(err.response))
    });

Here is node js express code app.js

app.delete("/notes/:notesId", cors(), function(req, res) {
  const query={_id:req.params.notesId};
  console.log("The notes id is "+ query);  
  Note.findOneAndDelete(query, function(err) {
    if(!err) {
      console.log("The item got successfully deleted");
      res.redirect("/");
    } else {
      console.log(err)
    }
  })
})

Please note that the entry gets deleted from my database but i get this error in my browser console :

xhr.js:178 DELETE http://localhost:8000/ 404 (Not Found)
App.jsx:26 There was an error {"data":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot DELETE /</pre>\n</body>\n</html>\n","status":404,"statusText":"Not Found","headers":{"content-length":"142","content-type":"text/html; charset=utf-8"},"config":{"url":"http://localhost:8000/notes/5ee130b65dc5f521acf60f38","method":"delete","headers":{"Accept":"application/json, text/plain, */*"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

I am trying to hit the complete url till notes id but it is only considering till root

Upvotes: 0

Views: 894

Answers (1)

spaceSentinel
spaceSentinel

Reputation: 670

Try modifying the res to send a 200 OK status if the object gets deleted. You could also send a message for your frontend to display in this manner

if(!err) {
    res.status(200).json({ message: 'The item got successfully deleted', error: false });
} else {
    res.status(500).json({message : 'Oops and error occurred', error : true});

Regardless a simple res.status(200).end(); should suffice as well for your situation.

Upvotes: 1

Related Questions