Menu
CoddyTech

顺序很重要

本课属于 Coddy Node.js 学习旅程的“Express 基础”单元。第 14 课,共 23 课。

Express 会按照代码添加中间件和路由的顺序运行它们,而会发送响应的路由会在此处结束请求。

app.get('/bikes', (req, res) => {
    res.json(bikes);
});

app.use((req, res, next) => {
    res.set('Cache-Control', 'no-store');
    next();
});

res.set(name, value) 会向响应添加一个响应头,并且必须在发送响应之前运行。这里,GET /bikes 会在执行到中间件之前发送响应,因此它的响应不会获得这个响应头:中间件只能看到上方没有路由处理的请求。需要处理每个响应的中间件,应放在路由和 express.static 上方。

challenge icon

挑战

简单

每个响应都会获得一个 id,这样当访客报告问题时,你就能在日志中找到他们的请求。每个响应都需要一个 id:页面、API 数据,以及来自 public 的文件。

  1. 在 server.js 中,从 node:crypto 导入 randomUUID。每次调用都会返回一个新的随机 id,例如 3b241101-e2bb-4255-8caf-4136c566a962。
  2. 添加一个中间件,为响应设置名为 X-Request-Id 的标头,其中包含每个请求对应的新 randomUUID(),然后调用 next()。
  3. 将它放在合适的位置,确保每个请求都会经过它,包括由 express.static 发送的文件。只有在中间件先于响应操作运行时,响应才会带有这个标头。

试试看:点击“运行”,发送两次 /api/recipes。在 Headers 选项卡中,X-Request-Id 每次的值都不同。发送 /style.css 和 /:它们也都带有 X-Request-Id。

亲手试试

import { escapeHtml } from './html.js';
import express from 'express';
import { recipes } from './data.js';

const app = express();

app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

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 在线编辑器