Menu
CoddyTech

更多路由

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

一个网站有多个页面,因此服务器需要为每个路径设置一条路由。

app.get('/books', (req, res) => {
    res.send('12 books on the shelf');
});

app.get('/opening-hours', (req, res) => {
    res.send('Monday to Friday, 10 to 6');
});

Express 会读取每个请求的路径,并调用与该路径对应的路由:GET /books会到达第一个函数,GET /opening-hours则会到达第二个函数。没有对应路由的路径会显示 Express 自带的 404 页面。路由的路径总是以/开头。

Recipe Box 又回来了,其中的data.js文件保存了四道菜谱,还有一条/recipes路由会列出它们的标题。

challenge icon

挑战

简单

Recipe Box 需要在主页和食谱列表旁边添加一个“关于”页面。

  1. 在 server.js 中找到注释 // Add the /about page here.,然后为路径 /about 添加一个路由。该路由发送以下句子,包括句号:Recipe Box collects family recipes.
  2. 保持 / 和 /recipes 路由不变。

试试看:点击“运行”,然后发送 /about。你应该会看到 Recipe Box collects family recipes.。发送 /recipes:四个食谱标题,每行一个。然后发送 /about-us。没有路由对应这个路径,因此 Express 会返回状态码 404 和 Cannot GET /about-us。请求栏中的路径列表会显示你的应用有哪些路由。

亲手试试

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

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Recipe Box');
});

// type('text') 会发送纯文本,因此每个标题各占一行。
app.get('/recipes', (req, res) => {
    res.type('text').send(recipes.map((recipe) => recipe.title).join('\n'));
});

// 在这里添加 /about 页面。

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

Express 基础中的所有课

自己练习: Express 在线编辑器