DELETE is used to remove resources from the server.
Note: DELETE requests typically don’t include a request body. All the information needed (like the user ID) is in the URL.
How DELETE Works
Now we’ll use app.delete() to create routes that handle DELETE requests.
From the frontend:
fetch("/users/1", { method: "DELETE" });
On the API side:
app.delete("/users/:id", (req, res) => {
const userId = Number(req.params.id);
// Check if ID is a valid number
if (isNaN(userId)) {
return res.status(400).json({ error: "Invalid user ID" });
}
// Find the user
const userIndex = users.findIndex((user) => user.id === userId);
if (userIndex === -1) {
return res.status(404).json({ error: "User not found" });
}
users.splice(userIndex, 1);
// Return 204 No Content (successful deletion)
res.status(204).send();
});
Key Points About DELETE
- No request body needed - Just the ID in the URL
- Return 204 No Content - Standard for successful deletion
- Use
splice()- Removes item from array and returns it - 404 if not found - Same as PUT/PATCH
Security note: This route would also require proper authentication and authorization.