Menu
CoddyTech

PUT으로 교체하기

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

수정 양식은 모든 필드를 한꺼번에 포함해 작업 전체를 다시 보냅니다. PUT은 “이것으로 리소스를 교체하라”는 뜻이므로 본문에는 모든 내용이 포함되어야 합니다.

PATCH /api/invoices/7  { "paid": true }               → paid changes
PUT   /api/invoices/7  { "amount": 90, "paid": true } → invoice 7 replaced
PUT   /api/invoices/7  { "paid": true }               → 400: amount missing

필드가 빠진 PUT 요청은 400 오류를 반환합니다. 청구서의 절반만으로 교체하면 금액이 사라지기 때문입니다. 서버가 관리하는 id와 생성 시간 같은 필드는 본문이 아니라 이전 버전에서 가져옵니다.

const { id, issuedAt } = invoices[index];
invoices[index] = { id, amount, paid, issuedAt };
challenge icon

챌린지

쉬움

편집 양식은 작업 전체를 한 번에 전송합니다. 클라이언트가 보내는 내용으로 작업을 대체하는 PUT 경로를 추가하세요.

  1. routes/tasks.js에 PUT /api/tasks/:id를 추가하세요. 본문에는 두 필드가 모두 있어야 합니다. 예를 들면 { "title": "Book the big room", "done": true }와 같습니다.
  2. 작업의 title과 done을 본문의 값으로 대체하세요. 저장된 작업의 id와 createdAt은 그대로 유지하고, 본문에서 가져오지 마세요. 상태 코드 200과 작업 전체를 응답하세요:
    { "id": 2, "title": "Book the big room", "done": true, "createdAt": "2026-03-03T10:30:00.000Z" }
  3. 본문에 title 또는 done이 없으면 상태 코드 400과 { "error": "PUT needs every field: title and done" }을 응답하고 아무것도 변경하지 마세요. 필드가 없다는 것은 본문에 해당 필드가 아예 없는 경우뿐입니다. "done": false는 유효한 값입니다.
  4. 해당 id를 가진 작업이 없으면 다른 경로와 마찬가지로 상태 코드 404와 { "error": "Task not found" }를 응답하세요.

직접 해보기: PUT /api/tasks/2에 { "title": "Book the big room", "done": true }를 보내면 상태 코드 200과 위 작업이 반환됩니다. 그런 다음 PUT /api/tasks/2에 { "done": true }만 보내면 상태 코드 400이 반환되고, GET /api/tasks/2에는 여전히 "Book the big room"이 표시됩니다. 두 필드를 모두 담아 PUT /api/tasks/99를 보내면 상태 코드 404가 반환됩니다.

직접 해보기

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);
});

router.delete('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return res.status(404).json({ error: 'Task not found' });
    }
    tasks.splice(index, 1);
    res.status(204).end();
});

export default router;
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

REST API의 모든 레슨

직접 연습해 보세요: Express 플레이그라운드