Home > Mobile >  Delete function successful but returnin catch err message | Node .js
Delete function successful but returnin catch err message | Node .js

Time:10-24

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

CodePudding user response:

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(...);.

CodePudding user response:

change it into idk but how can Sequelize using a lowerCase ? but nvm

app.delete("/delete/items/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const find = await items.finByPk(id);
    if (!find) throw new Error("Data Not Found");
    const deleted = await items.destroy({ where: { id } });
    res.status(200).json({ message: `Deleted item with ID : ${deleted.id}` });
  } catch (error) {
    res.status(500).json(error);
  }
});

for the status it wasnt might be 500 ig, it used to be 401 400 because of u cannot to access the action but also can access the db

  • Related