To remove something, a client uses the DELETE method and names what to remove in the path. DELETE /products/2 has the same path as GET /products/2, but a different method, so Express sends it to a different function.
An array's indexOf gives the position of an item (or -1 when it isn't there), and splice(index, 1) removes 1 element at that position. After a delete there is nothing to send back, so the answer is an empty body with the status 204 No Content. Here is the idea on another route:
const tags = ["new", "sale", "gift"];
app.delete("/tags/:name", (req, res) => {
const index = tags.indexOf(req.params.name);
if (index === -1) {
return res.status(404).json({ error: "Tag not found" });
}
tags.splice(index, 1);
res.status(204).send();
});
Your shop finds the product with a loop, like the route that reads one product, and answers 404 with the same error when no product has that id. Your code must give, in this order:
DELETE /products/2 → 204 (empty body)
GET /products/2 → 404 {"error": "Product not found"}
GET /products → 200 [{"id": 1, …}, {"id": 3, …}, {"id": 4, …}]
DELETE /products/2 → 404 {"error": "Product not found"}
DELETE /products/99 → 404 {"error": "Product not found"}
GET /products/count → 200 {"count": 3}
POST /products {"name": "Plant", "price": 15, "category": "home"} → 201 {"id": 5, "name": "Plant", "price": 15, "category": "home"}
Your task: add a DELETE /products/:productId route that removes the product with that id and answers 204 with an empty body, or 404 with {"error": "Product not found"} when there is no such product.
Assignment
Follow the Coding Tutorial to build the DELETE route for one product.
Hint
Find the product with the same loop as in the route that reads one product. Return right after splice, inside the loop; the 404 goes after the loop, at the level of for.
Free plan: 30 tutor messages. PRO is unlimited.
