每日食谱
本课属于 Coddy Node.js 学习旅程的“Express 基础”单元。第 22 课,共 23 课。
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。有 4 道食谱时,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,则返回状态码 400 和{"error":"Use a date like 2026-03-01"}。 - 否则,等待
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 在线编辑器