你的第一个中间件
本课属于 Coddy Node.js 学习旅程的“Express 基础”单元。第 13 课,共 23 课。
有些工作适用于每个请求,比如向日志中写入一行内容。把这项工作复制到每个路由中,永远也做不完。每个请求都有一个方法,位于 req.method 中:GET 用于获取内容,POST 用于发送内容。
let visits = 0;
app.use((req, res, next) => {
visits++;
next();
});传给 app.use 的函数就是中间件:Express 会按照添加顺序,在下面的路由之前为每个请求运行它。它会接收第三个参数 next。调用 next() 会把请求交给接下来要处理它的内容。既不响应请求也不调用 next() 的中间件会让请求一直等待下去。
上一章介绍的 express.static 也是中间件:找到文件时,它会响应请求;找不到时,它会调用 next()。
挑战
简单你想为服务器收到的每个请求记录一行日志,这样就能看到访客请求了什么。
- 在
server.js中,紧接着const app = express();后面,使用app.use添加中间件。放在这里,它会在每个路由之前运行。 - 对于每个请求,它都会在控制台打印一行:请求的方法、一个空格,然后是请求路径。请求
/recipes/2会打印GET /recipes/2。方法在req.method中(GET、POST等),路径在req.url中。 - 打印后,它会调用
next(),这样请求就会继续传给各个路由。
试试看:点击“运行”,然后发送 /recipes/2。你应该会看到 Pancakes,控制台中会显示 GET /recipes/2。发送 /api/recipes:会像往常一样返回列表,控制台中会显示 GET /api/recipes。发送 /nope:会得到 404,控制台仍会显示 GET /nope,因为中间件会在 Express 查找路由之前运行。
亲手试试
import { escapeHtml } from './html.js';
import express from 'express';
import { recipes } from './data.js';
const app = express();
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.get('/api/recipes', (req, res) => {
res.json(recipes);
});
app.get('/api/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
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.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Express 基础中的所有课
自己练习: Express 在线编辑器