Menu
CoddyTech

重定向

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

页面会发生变化,书签和搜索结果中的旧链接也应该仍然能带你访问相应页面。

app.get('/old-prices', (req, res) => {
    res.redirect(301, '/prices');
});

重定向会返回一个状态码和一个 Location 标头,其中写明新的 URL,浏览器会立即请求该 URL。res.redirect 会同时设置这两项。

状态码说明这次迁移会持续多久。301 表示永久迁移:浏览器和搜索引擎会记住新地址,不再请求旧地址。302 是未指定状态码时的默认值,表示暂时迁移,因此它们会继续使用旧 URL。

challenge icon

挑战

简单

旧菜单页面已永久迁移到食谱页面,旧书签仍然应该可以使用。

  1. 在 server.js 中,为 /menu 添加一个路由,将请求重定向到 /recipes,状态码为 301,表示永久迁移。
  2. 添加一个 /menu/:id 路由,将请求重定向到具有相同 id 的食谱页面,状态码同样为 301:/menu/3 会跳转到 /recipes/3。

试一试:点击“运行”,然后发送 /menu/3。你应该会看到状态码 301,以及值为 /recipes/3 的 Location 标头。发送 /menu:状态码为 301,Location 的值为 /recipes。发送 /menu/42:状态码为 301,Location 的值为 /recipes/42。重定向不会检查食谱 42 是否存在;之后 /recipes/42 本身会返回 404。

亲手试试

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.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

Express 基础中的所有课

自己练习: Express 在线编辑器