Consider this Express DELETE route that removes an item by ID from an array. What will the server respond with if the item exists?
const express = require('express'); const app = express(); app.use(express.json()); let items = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}]; app.delete('/items/:id', (req, res) => { const id = Number(req.params.id); const index = items.findIndex(item => item.id === id); if (index === -1) { return res.status(404).send('Item not found'); } items.splice(index, 1); res.status(200).send('Deleted'); });
Check what happens when the item is found and removed.
If the item exists, the route removes it and sends status 200 with 'Deleted'. If not found, it sends 404.
Which of the following Express DELETE route definitions is syntactically correct?
Look for balanced parentheses and braces.
Option B has correct arrow function syntax with balanced braces and parentheses.
Given this DELETE route, why does the server crash when a request is made?
app.delete('/users/:id', (req, res) => { const id = Number(req.params.id); const user = users.find(u => u.id === id); users = users.filter(u => u.id !== id); res.send(`Deleted user ${user.name}`); });
Check the type of id and how find works.
req.params.id is a string, but user ids are numbers, so find returns undefined. Accessing user.name causes a runtime error.
Given this initial array and DELETE route, what is the content of items after a DELETE request to /items/2?
let items = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'cherry'}];
app.delete('/items/:id', (req, res) => {
const id = Number(req.params.id);
items = items.filter(item => item.id !== id);
res.status(200).send('Deleted');
});Filter removes items with matching id.
The item with id 2 is removed, so only items with id 1 and 3 remain.
When designing an Express DELETE route, which response practice is recommended for RESTful APIs?
Think about HTTP status codes and REST conventions.
HTTP 204 No Content is the standard response for successful DELETE with no body.