Deleting
Part of the REST APIs section of Coddy's Node.js journey. Lesson 4 of 18.
After a delete there is nothing left to show the client. The answer for that is 204 No Content: the request worked and the body is empty.
DELETE /api/events/5 → 204 No Content
DELETE /api/events/5 → 404 Not FoundThe second request finds no event 5, so it answers 404 like a GET for an unknown id. To remove an item from an array, find its position with findIndex, which gives -1 when nothing matches, and cut it out with splice:
events.splice(index, 1); // remove 1 item at index
res.status(204).end(); // a status and no bodyChallenge
EasyDELETE /api/tasks/:idremoves the task and answers 204 with no body.- An unknown id answers 404 with
{ "error": "Task not found" }.
Send DELETE /api/tasks/3 twice, then GET /api/tasks.
Try it yourself
import { Router } from 'express';
import { nextId, tasks } from '../store.js';
const router = Router();
router.get('/', (req, res) => {
res.json(tasks);
});
router.get('/:id', (req, res) => {
const task = tasks.find((t) => t.id === Number(req.params.id));
if (!task) {
return res.status(404).json({ error: 'Task not found' });
}
res.json(task);
});
router.post('/', (req, res) => {
const { title } = req.body ?? {};
if (!title) {
return res.status(400).json({ error: 'title is required' });
}
const task = { id: nextId(), title, done: false, createdAt: new Date().toISOString() };
tasks.push(task);
res.status(201).location(`/api/tasks/${task.id}`).json(task);
});
router.patch('/:id', (req, res) => {
const task = tasks.find((t) => t.id === Number(req.params.id));
if (!task) {
return res.status(404).json({ error: 'Task not found' });
}
const { title, done } = req.body ?? {};
if (title !== undefined) task.title = title;
if (done !== undefined) task.done = done;
res.json(task);
});
export default router;
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST