Menu
CoddyTech

삭제하기

Coddy Node.js 여정의 REST API 섹션에 포함된 레슨. 18개 중 4번째.

삭제 후에는 클라이언트에 표시할 내용이 남아 있지 않습니다. 이에 대한 응답은 204 No Content입니다. 요청이 성공했고 본문은 비어 있습니다.

DELETE /api/events/5   →  204 No Content
DELETE /api/events/5   →  404 Not Found

두 번째 요청은 이벤트 5를 찾지 못하므로, 알 수 없는 id에 대한 GET 요청과 마찬가지로 404를 응답합니다. 배열에서 항목을 제거하려면 findIndex로 위치를 찾으세요. 일치하는 항목이 없으면 -1을 반환하며, splice로 해당 항목을 잘라 냅니다.

events.splice(index, 1);   // index 위치의 항목 1개를 제거
res.status(204).end();     // 상태 코드만 있고 본문은 없음
challenge icon

챌린지

쉬움
  • DELETE /api/tasks/:id는 작업을 삭제하고 본문 없이 204로 응답합니다.
  • 알 수 없는 id에는 { "error": "Task not found" }와 함께 404로 응답합니다.

DELETE /api/tasks/3을 두 번 보낸 다음 GET /api/tasks를 보내세요.

직접 해보기

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;

REST API의 모든 레슨