Express 라우터
Coddy Node.js 여정의 Express 기초 섹션에 포함된 레슨. 20개 중 16번째.
server.js에는 이제 페이지, API 경로, 미들웨어가 들어 있으며, 계속 커지고 있습니다.
// routes/books.js
const router = express.Router();
router.get('/', (req, res) => res.json(books));
router.get('/:isbn', (req, res) => res.json(findBook(req.params.isbn)));
export default router;
// server.js
app.use('/api/books', booksRouter);express.Router()는 자체 경로를 가진 작은 앱을 만들어 별도의 파일에 둡니다. app.use('/api/books', booksRouter)는 이를 마운트합니다. 라우터의 /는 GET /api/books에 응답하고, /:isbn은 GET /api/books/9780141439518에 응답합니다. 접두사는 app.use에 한 번만 작성합니다. 라우터 내부에서 발생한 오류도 여전히 앱의 오류 처리기에 전달됩니다.
새 파일 routes/recipes.js에는 이미 경로 하나인 /tags가 있습니다.
챌린지
쉬움/api/recipes의 네 개 경로를server.js에서routes/recipes.js의/tags아래로 옮기세요.- 라우터를
/api/recipes에 마운트하세요.
GET /api/recipes/tags, GET /api/recipes/2 및 GET /api/recipes/2/scale?by=lots를 보내세요.
직접 해보기
import express from 'express';
import { recipes } from '../data.js';
const router = express.Router();
// 모든 태그를 알파벳순으로, 각각 한 번씩.
router.get('/tags', (req, res) => {
const tags = new Set(recipes.flatMap((recipe) => recipe.tags));
res.json([...tags].sort());
});
// server.js의 /api/recipes 라우트들을 여기 /tags 아래로 옮기세요.
// router 내부에서 경로는 router가 마운트된 위치를 기준으로 하는 상대 경로입니다.
export default router;
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.