Skip to content
Advertisement

Delete function successful but returnin catch err message | Node .js [closed]

i have a destroy function

app.delete('/delete/items/:id', async(req, res) => {
  const id =  req.params.id;
  items.destroy({
    where:{
      id: id
    }
  }).then(res => {
    res.status(200).json("Items deleted")
  }).catch(err => {
    res.status(500).json("Can't delete Items")
  })
 })

the delete is working but it keeps returning the “Can’t delete items” POSTMAN

Database

Advertisement

Answer

to answer this question the error is, TypeError: res.status is not a function. i’m using res.status in my other function it’s running well, why this happen only in destroy function?

OK, that’s because you’re redefining the res variable with something else in your item.destroy(...).then(res => {... });. This res then replaces access to the res from the request (hiding it). Change that second res to some other variable name:

app.delete('/delete/items/:id', (req, res) => {
  const id =  req.params.id;
  items.destroy({
    where:{
      id: id
    }
  }).then(data => {                            // changed res to data here
    res.json("Items deleted");
  }).catch(err => {
    console.log(err);                          // always log error
    res.status(500).json("Can't delete Items");
  })
 })

Another morale to the story here is to ALWAYS log your errors on the server so you don’t get confused about what’s going on when it hits an error path.

FYI, .status(200) is unnecessary as 200 is already the default status. So, you can also change res.status(200).json(...); to res.json(...);.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement