[Vuejs]-What is wrong with the delete portion of my API?

0👍

As you can see in url you are not getting params id its showing as undefined
//fakeDomainName.com:3010/api/candidates/undefined
due to which it is giving error if you will pass with as id it will work as well

//delete a candidate from the list
    app.delete('/api/candidates/:id', async(req, res) => {
      console.log("initiated delete request");
      Candidate.findOneAndDelete({ _id: req.params.id }, function(err) {
        if (err) res.sendStatus(500);
        else {
          console.log(req.params.id, "deleted successfully");
          res.sendStatus(200);
        }
      });
    });```

0👍

I tested your node side with postman. “Delete” is fine. But as you see in the error itself
DELETE http://fakeDomainName.com:3010/api/candidates/undefined the parameter item id is being sent undefined, hence cannot delete.

In you POST request (on server/node side), you can perhaps add a sendStatus(200) to avoid post request being hung up.Also, You can get id of the saved item while saving the Candidate

Like this:

    app.post('/api/candidates', async(req, res) => {
  console.log("initiated post request");
  const candidate = new Candidate({
    name: req.body.name,
    bio: req.body.bio,
    numVotes: req.body.numVotes,
  });
  this.addItem = candidate.data;
  try {
      console.log("Await save...");
    let data = await candidate.save();
    console.log("Done");
    res.statusCode = 200;
    res.setHeader('content-type','application/json');
    res.end(JSON.stringify(data));
  }
  catch (error) {
    console.log(error);
    res.sendStatus(500);
  }
});

The response would be like :

{
"_id": "5dd38cb16f47912b40a1deef",
"name": "Ken Adams",
"bio": "bio",
"numVotes": "10",
"__v": 0

}

Leave a comment