1

I am trying to get my DELETE method to work. When the function is ran it is going straight into the throw Error line. In the console it is printing the following two errors. “404 Not Found” “Error Uncaught (in promise) Error"

Here is my client side code

async function deleteItem(item) {
  let requestOptions = {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  }

  const response = await fetch("/delete/:id", requestOptions);
  if (response.status != 204) {
    throw Error("Cannot delete your item from list");
  }
  return item;
}

And server side code

app.delete("/delete/:id"),
  async (request, res) => {
    try {
      await Item.deleteOne({ _id: request.params.id });
      res.sendStatus(204);
    } catch {
      res.sendStatus(404);
      console.log('test');
    }
  };
  • Don't ignore the thrown error in your server-side `try`/`catch` statement. Instead of printing `test`, at least log the error message! – Bergi Dec 16 '20 at 12:07

2 Answers2

3

You need to pass the ID of the "thing" that you want to delete in the client side code.

async function deleteItem(item) {
  let requestOptions = {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  }

  const response = await fetch("/delete/:id", requestOptions); // <----- HERE! 
  if (response.status != 204) {
    throw Error("Cannot delete your item from list");
  }
  return item;
}

it should be something like (assuming that the item object has the id)

const response = await fetch(`/delete/${ item.id }`, requestOptions);

e.g.: /delete/12423

cape_bsas
  • 638
  • 5
  • 13
  • I have declared a global const for my PUT method to retrieve the ID but when trying to use the same const it throws me the same error I previously had ```const itemId = url.searchParams.get("id");``` is how my PUT is retrieving the correct id for updating my ```item``` – Jeffery Kimbrow Dec 15 '20 at 23:13
0

You aren't catching the promise returned from your fetch() function causing it to throw an error. Also, it looks like you aren't sending the request with a valid id. You could fix that by doing

fetch(...).then((response) => {
    if (response.status != 204) {
      throw Error("Cannot delete your item from list");
    }
}).catch((err) => {
    console.error(err); // handle error
});

or

const response = await fetch(...).catch((err) => {
    console.error(err); // handle error
});
// if the promise is rejected and the catch block is executed then 'response' will be undefined
if (!response) return;
if (response.status != 204) {
    throw Error("Cannot delete your item from list");
}

edit: or of course you could not catch the promise rejection and just send the request with a valid id