Menu
CoddyTech

静态文件

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

样式表或图片不会改变,为每个文件都设置一条路由只是徒增工作。

app.use(express.static('assets'));

express.static('assets')会以文件自身的名称提供assets文件夹中的文件:assets/logo.png会响应GET /logo.png。文件夹名称不会出现在 URL 中。Express 会根据扩展名选择内容类型:.css对应text/css,.png对应image/png。如果路径下没有文件,请求就会继续传给你的路由。

app.use会添加一个对每个请求都会运行的函数;下一章会介绍这些函数。现在,你的项目中有一个包含样式表的public文件夹。

challenge icon

挑战

简单

Recipe Box 有了样式表。文件已放在 public 文件夹中,服务器只需把它提供出去。

  1. 在 server.js 中,紧接着 const app = express();,使用 express.static 提供 public 文件夹中的所有文件。这样,public/style.css 就会通过 /style.css 提供。
  2. 让主页加载样式表:将 <link rel="stylesheet" href="/style.css"> 放在 / 路由发送的 HTML 开头。

试试看:按“运行”,然后发送 /。现在页面会使用样式表。发送 /style.css:状态码为 200,返回 CSS 文本,并且在 Headers 选项卡中,Content-Type 为 text/css。发送 /missing.css:没有这个文件,因此请求会继续传递到你的路由。没有路由匹配,Express 会返回 404。

亲手试试

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

const app = express();



app.get('/', (req, res) => {
    const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
    res.send(`<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 在线编辑器