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.
Practice
DELETE route in Express?Solution
Step 1: Understand HTTP methods
HTTP methods define actions: GET retrieves, POST adds, PUT updates, DELETE removes.Step 2: Identify DELETE route purpose
DELETE routes specifically handle requests to remove data from the server.Final Answer:
To remove data from the server -> Option CQuick Check:
DELETE = remove data [OK]
- Confusing DELETE with POST or GET
- Thinking DELETE adds or updates data
- Assuming DELETE retrieves data
/items/:id in Express?Solution
Step 1: Identify HTTP method for deletion
DELETE method is used to remove resources, soapp.deleteis correct.Step 2: Check route path and handler syntax
The path/items/:idwith a callback function matches Express route syntax.Final Answer:
app.delete('/items/:id', (req, res) => { /* handler */ }); -> Option AQuick Check:
DELETE route syntax = app.delete(path, handler) [OK]
- Using app.get or app.post instead of app.delete
- Missing the callback function
- Incorrect path format
DELETE /users/5 and the user with id 5 exists?
const users = [{id: 1}, {id: 5}, {id: 9}];
app.delete('/users/:id', (req, res) => {
const id = Number(req.params.id);
const index = users.findIndex(u => u.id === id);
if (index !== -1) {
users.splice(index, 1);
res.status(200).send('User deleted');
} else {
res.status(404).send('User not found');
}
});Solution
Step 1: Check if user with id 5 exists
The array contains {id: 5}, so index will not be -1.Step 2: Analyze response when user found
Since index !== -1, user is removed and response status 200 with 'User deleted' is sent.Final Answer:
Response status 200 with message 'User deleted' -> Option AQuick Check:
User exists = 200 'User deleted' [OK]
- Assuming 404 even if user exists
- Confusing status codes
- Not converting id to number before comparison
app.delete('/products/:id', (req, res) => {
const id = req.params.id;
const product = products.find(p => p.id === id);
if (!product) {
res.status(404).send('Product not found');
}
products = products.filter(p => p.id !== id);
res.send('Product deleted');
});Solution
Step 1: Check flow after 404 response
If product not found, res.status(404).send is called but code continues without return.Step 2: Identify multiple responses sent
After 404 response, code still filters products and calls res.send again, causing error.Final Answer:
res.send called twice without return -> Option DQuick Check:
Multiple res.send calls without return cause errors [OK]
- Not returning after sending 404 response
- Ignoring type conversion for id
- Assuming route path is wrong
const library = {
fiction: [{id: 1, title: 'A'}, {id: 2, title: 'B'}],
nonFiction: [{id: 3, title: 'C'}]
};
app.delete('/books/:id', (req, res) => {
const id = Number(req.params.id);
let found = false;
for (const genre in library) {
const index = library[genre].findIndex(book => book.id === id);
if (index !== -1) {
library[genre].splice(index, 1);
found = true;
break;
}
}
if (found) {
res.status(200).send('Book deleted');
} else {
res.status(404).send('Book not found');
}
});Solution
Step 1: Check id conversion
id is converted to Number, ensuring correct comparison with book ids.Step 2: Verify loop and deletion logic
Loop checks each genre, finds book by id, deletes it, sets found true, and breaks loop to avoid extra deletions.Step 3: Confirm response handling
If found is true, sends 200 with 'Book deleted'; else sends 404 with 'Book not found'.Final Answer:
This code correctly deletes the book and handles 404 if not found -> Option BQuick Check:
Proper id conversion, deletion, and response = correct code [OK]
- Not converting id to number before comparison
- Not breaking loop after deletion
- Sending success response even if book missing
Ready to prove it?
Pass the test and this pattern moves unknown
