DELETE route handling lets your server remove data when a client asks for it. It helps keep your app's data up to date by deleting items.
DELETE route handling in Express
app.delete('/path', (req, res) => { // code to delete resource res.send('Deleted successfully'); });
The app.delete method defines a route that listens for DELETE requests.
The callback function receives req (request) and res (response) objects to handle the request and send a response.
app.delete('/items/:id', (req, res) => { const id = req.params.id; // delete item with this id res.send(`Item ${id} deleted`); });
app.delete('/users', (req, res) => { // delete all users res.send('All users deleted'); });
This Express app has a list of books. The DELETE route removes a book by its ID from the URL. If the book exists, it deletes and confirms. If not, it sends a 404 error.
import express from 'express'; const app = express(); const port = 3000; // Sample data let books = [ { id: 1, title: 'Book One' }, { id: 2, title: 'Book Two' }, { id: 3, title: 'Book Three' } ]; // DELETE route to remove a book by id app.delete('/books/:id', (req, res) => { const bookId = Number(req.params.id); const index = books.findIndex(book => book.id === bookId); if (index !== -1) { books.splice(index, 1); res.status(200).send(`Book with id ${bookId} deleted.`); } else { res.status(404).send('Book not found.'); } }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
DELETE routes usually do not send back the deleted data, just a confirmation message.
Always check if the item to delete exists to avoid errors.
Use proper HTTP status codes like 200 for success and 404 if the item is not found.
DELETE routes handle requests to remove data from the server.
Use app.delete with a path and a callback function.
Always confirm deletion or handle errors if the item is missing.