🎯 第 17 课:Express 核心三剑客

0 阅读3分钟

太棒了!👏 你已经决定使用 Express 这把“利器”,现在我们深入它的核心机制:


🔧 路由(Routing) + 中间件(Middleware) + 请求与响应对象(req/res)

我们将逐一拆解这三大核心概念,让你真正掌握 Express 的“内功心法”。


🗺️ 第一剑:路由(Routing)

📌 什么是路由?

定义你的服务器如何响应特定 URL 和 HTTP 方法的请求。

✅ 基本语法

app.METHOD(path, handler)
  • METHOD:HTTP 方法,如 get, post, put, delete
  • path:客户端请求的路径
  • handler:处理请求的函数 (req, res) => { ... }

💡 示例

const express = require('express');
const app = express();

// GET /
app.get('/', (req, res) => {
  res.send('首页');
});

// GET /about
app.get('/about', (req, res) => {
  res.send('<h1>关于我们</h1>');
});

// POST /login
app.post('/login', (req, res) => {
  res.json({ message: '登录成功!' });
});

🧩 高级路由技巧

1. 路径参数(Params)

用于动态路径,比如用户 ID:

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`查看用户 ${userId}`);
});

// /users/123 → 输出: 查看用户 123

支持多个参数:

app.get('/users/:id/posts/:postId', (req, res) => {
  res.send(`用户 ${req.params.id} 的文章 ${req.params.postId}`);
});

2. 查询参数(Query)

自动解析 ?key=value

app.get('/search', (req, res) => {
  const keyword = req.query.q;
  res.send(`搜索关键词: ${keyword}`);
});

// /search?q=node → 输出: 搜索关键词: node

⚙️ 第二剑:中间件(Middleware)

📌 什么是中间件?

一个函数,可以访问 reqres 和下一个中间件 next(),用于执行:

  • 修改请求或响应对象
  • 结束请求-响应周期(如返回错误)
  • 调用下一个中间件

✅ 基本结构

function middleware(req, res, next) {
  // 做点事...
  console.log('请求时间:', Date.now());

  // 继续下一个中间件或路由
  next();
}

🔧 使用方式:app.use()

app.use(middleware);

👉 所有请求都会经过它!


💡 实战示例:常用中间件

1. 日志中间件(记录每个请求)

app.use((req, res, next) => {
  console.log(`${req.method} ${req.path} - ${new Date().toISOString()}`);
  next(); // 别忘了调用 next()!
});

输出:

GET / - 2025-04-05T10:00:00.123Z
GET /about - 2025-04-05T10:00:05.456Z

2. 解析 JSON 请求体

app.use(express.json());

这样你就能在 POST 请求中使用 req.body 了:

app.post('/api/user', (req, res) => {
  console.log(req.body); // { name: "Alice", age: 20 }
  res.json({ id: 1, ...req.body });
});

3. 处理表单数据(application/x-www-form-urlencoded)

app.use(express.urlencoded({ extended: true }));

extended: true 支持复杂对象解析。


🛑 中间件顺序很重要!

app.use((req, res, next) => {
  console.log('第一步');
  next();
});

app.use((req, res, next) => {
  console.log('第二步');
  next();
});

app.get('/', (req, res) => {
  console.log('第三步:处理请求');
  res.send('完成');
});

输出顺序:

第一步
第二步
第三步:处理请求

✅ 正确!但如果某个中间件没有调用 next(),后面的就不会执行!


📥📤 第三剑:请求与响应对象详解

🔹 req(请求对象)—— 客户端发来的信息

属性说明
req.path请求路径,如 /users
req.method请求方法,如 GETPOST
req.query查询参数对象 { q: 'node' }
req.params路径参数 { id: '123' }
req.body请求体(需启用 express.json()
req.headers请求头信息

🔹 res(响应对象)—— 我们返回给客户端的内容

方法说明
res.send(body)发送字符串、HTML 或 JSON
res.json(obj)自动设置 Content-Type: application/json 并发送 JSON
res.status(code)设置状态码(链式调用)
res.sendFile(path)发送一个文件
res.redirect(url)重定向

💡 示例组合技

res.status(404).send('页面找不到了 😢');

res.status(201).json({ msg: '创建成功' });

res.sendFile(__dirname + '/public/index.html');

✅ 小结一句话:

Express 的三大核心是:

  • 路由:定义谁来处理哪个请求
  • 中间件:在请求过程中“插一脚”做些事
  • req/res:获取输入、返回输出,贯穿始终

📬 下一课预告:
第 18 课:实战项目③ —— 用 Express 搭建一个博客 API(支持增删改查)

我们将综合运用今天所学,做一个真正的:

  • GET /posts → 获取所有文章
  • POST /posts → 添加新文章
  • DELETE /posts/1 → 删除文章