오늘의 레시피
Coddy Node.js 여정의 Express 기초 섹션에 포함된 레슨. 23개 중 22번째.
Recipe Box는 익숙한 경로 처리 및 파일 읽기 기술을 활용해 하루에 하나의 레시피를 제공할 수 있습니다. 제공된 dayOfYear 도우미는 날짜를 숫자로 변환합니다. 1월 1일은 1이고 2026년 3월 1일은 60입니다. 날짜가 없으면 오늘 날짜를 사용하고, 읽을 수 없는 텍스트는 null을 반환합니다.
const day = dayOfYear(req.query.date);
// ?date=2026-03-01은 60을 반환합니다
// ?date=soon은 null을 반환합니다나머지 연산자를 사용해 위치를 선택하세요: day % recipes.length. 레시피가 네 개라면 day 60은 위치 0을 선택합니다. 최근에 게시된 레시피도 포함되도록 요청 처리 중에 레시피를 불러오세요. 날짜 파싱은 이미 제공되어 있으니 경로를 구성하는 데 집중하세요.
챌린지
쉬움Recipe Box에 오늘의 레시피 엔드포인트를 추가하세요. 제공된 day-of-year.js는 dayOfYear(text)를 내보내며, 날짜가 유효하지 않으면 날짜 번호 또는 null을 반환합니다.
routes/recipes.js에서loadRecipes를 내보내세요. 이를server.js로 가져오세요. 라우터는 기본 가져오기로 유지하고, 쉼표 뒤에{ loadRecipes }를 두세요.dayOfYear를 가져오세요.server.js에서 404 처리기 위에GET /api/today를 위한async라우트를 추가하세요.req.query.date를 헬퍼에 전달하세요.null이면{"error":"Use a date like 2026-03-01"}과 함께 400을 반환하세요.- 그렇지 않으면
loadRecipes()를 기다린 다음recipes[day % recipes.length]를 JSON으로 반환하세요. 기존 라우트와 오류 처리기는 그대로 두세요.
GET /api/today?date=2026-03-01을 시도해 보세요. 날짜 번호가 60이고 레시피가 네 개이므로 첫 번째 레시피가 반환됩니다. ?date=soon을 시도해 보세요. 위의 400 오류가 반환됩니다.
직접 해보기
import { escapeHtml } from './html.js';
import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
import recipesRouter from './routes/recipes.js';
import reviewsRouter from './routes/reviews.js';
const app = express();
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.use((req, res, next) => {
res.set('X-Request-Id', randomUUID());
next();
});
app.use(express.json());
app.use(express.static('public'));
app.get('/', (req, res) => {
const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});
// type('text')는 일반 텍스트를 전송하므로 각 제목이 한 줄씩 표시됩니다.
app.get('/recipes', (req, res) => {
const { tag } = req.query;
const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});
app.get('/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.send(recipe.title);
});
app.use('/api/recipes', recipesRouter);
app.use('/api/recipes/:id/reviews', reviewsRouter);
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.get('/menu', (req, res) => {
res.redirect(301, '/recipes');
});
app.get('/menu/:id', (req, res) => {
res.redirect(301, `/recipes/${req.params.id}`);
});
app.use((req, res) => {
if (req.path.startsWith('/api/')) {
res.status(404).json({ error: 'Not found' });
return;
}
res.status(404).send('<h1>Page not found</h1><p><a href="/">Back to Recipe Box</a></p>');
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Something went wrong' });
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
Express 기초의 모든 레슨
직접 연습해 보세요: Express 플레이그라운드