POST로 생성하기
Coddy Node.js 여정의 REST API 섹션에 포함된 레슨. 18개 중 2번째.
작업을 추가하는 클라이언트는 새 작업이 어디에 있는지 알아야 합니다. 클라이언트는 새 리소스를 POST를 사용해 목록의 URL로 보내고, 서버는 리소스와 해당 URL을 나타내는 Location 헤더를 포함해 201 생성됨으로 응답합니다.
POST /api/events { "name": "Launch party" }
201 Created
Location: /api/events/12
{ "id": 12, "name": "Launch party" }서버가 id를 선택하므로 두 클라이언트가 같은 id를 차지할 수는 없습니다. Location 헤더를 사용하면 클라이언트는 URL을 직접 만들지 않고도 새 이벤트를 가져올 수 있습니다. res.location(path)은 해당 헤더를 설정하며, res.status처럼 연결해서 사용할 수 있습니다.
res.status(201).location(`/api/events/${event.id}`).json(event);챌린지
쉬움POST /api/tasks에{ "title" }을 보내면 새 작업과 함께 201을 응답합니다. 새 작업에는store.js의nextId()에서 가져온id,done: false,new Date().toISOString()에서 가져온createdAt이 포함됩니다.Location을/api/tasks/<id>로 설정합니다.title이 없으면 400을 응답합니다.
{ "title": "Order new chairs" }를 보내고, 이어서 Location 경로에 GET 요청을 보낸 다음, {}를 POST하세요.
직접 해보기
import { Router } from 'express';
import { 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);
});
export default router;