618 Express.js REST API
一句话概述:Express 是 Node.js 最流行的 Web 框架,极简且灵活,海量中间件生态,几乎是 Node.js 后端开发的标配,PayPal、Uber 等大公司都在用。
核心知识点速查表
| 知识点 | 说明 |
|---|
| 最新版本 | Express 5.2.x(2025年底发布) |
| Node.js要求 | 18+(Express 5) |
| 核心特性 | 路由、中间件、模板引擎 |
| 生态 | 数千个 npm 中间件包 |
| 适用场景 | REST API、Web应用、微服务 |
一、安装与基本使用
mkdir my-api && cd my-api
npm init -y # 初始化 Node.js 项目
npm install express # 安装 Express
// app.js
import express from 'express'; // 导入 Express(ES模块语法)
const app = express(); // 创建应用
const PORT = 3000;
app.use(express.json()); // 解析 JSON 请求体(内置中间件)
// GET - 获取所有用户
let users = [
{ id: 1, name: '张三', email: 'zhangsan@example.com' },
{ id: 2, name: '李四', email: 'lisi@example.com' }
];
app.get('/api/users', (req, res) => { // GET 路由
const { name } = req.query; // 获取查询参数 ?name=xxx
let result = users;
if (name) {
result = users.filter(u => u.name.includes(name)); // 过滤
}
res.json(result); // 返回 JSON
});
// GET - 获取单个用户
app.get('/api/users/:id', (req, res) => { // :id 是路径参数
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: '用户不存在' });
res.json(user);
});
// POST - 创建用户
app.post('/api/users', (req, res) => {
const { name, email } = req.body; // 获取请求体
if (!name || !email) {
return res.status(400).json({ error: '缺少必填字段' });
}
const user = { id: users.length + 1, name, email };
users.push(user);
res.status(201).json(user); // 201 Created
});
// PUT - 更新用户
app.put('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: '用户不存在' });
Object.assign(user, req.body); // 合并更新字段
res.json(user);
});
// DELETE - 删除用户
app.delete('/api/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.status(204).send(); // 204 No Content
});
app.listen(PORT, () => console.log(`服务运行在 http://localhost:${PORT}`));
二、中间件
// 白话:中间件 = 请求和响应之间的"关卡",每个请求都要过关
import cors from 'cors'; // npm install cors
import helmet from 'helmet'; // npm install helmet(安全头)
import morgan from 'morgan'; // npm install morgan(日志)
app.use(cors()); // 允许跨域
app.use(helmet()); // 添加安全响应头
app.use(morgan('dev')); // 请求日志
// 自定义中间件:认证检查
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: '未认证' });
// 验证 token...
next(); // 调用 next() 继续下一个中间件/路由
};
app.use('/api/protected', authMiddleware); // 只对 /api/protected 路径生效
三、路由模块化
// routes/users.js
import { Router } from 'express';
const router = Router();
router.get('/', (req, res) => res.json([]));
router.post('/', (req, res) => res.status(201).json(req.body));
export default router;
// app.js 中使用
import userRoutes from './routes/users.js';
app.use('/api/users', userRoutes); // 挂载到 /api/users 路径
四、错误处理
// 统一错误处理中间件(必须4个参数)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: err.message || '服务器内部错误'
});
});
// Express 5 支持 async 错误自动捕获
app.get('/data', async (req, res) => {
const data = await fetchData(); // 如果抛异常,Express 5 自动传给错误处理
res.json(data);
});
五、常见报错与解决
| 问题 | 解决 |
|---|
Cannot GET /path | 检查路由定义是否匹配 |
| CORS 错误 | npm install cors + app.use(cors()) |
req.body is undefined | 确保 app.use(express.json()) 在路由之前 |
| Express 4 async 错误不捕获 | 升级到 Express 5 或手动 try-catch |
六、速查表
| 操作 | 代码 |
|---|
| GET 路由 | app.get('/path', handler) |
| POST 路由 | app.post('/path', handler) |
| 路径参数 | req.params.id |
| 查询参数 | req.query.key |
| 请求体 | req.body |
| JSON 响应 | res.json(data) |
| 状态码 | res.status(201).json(data) |
| 中间件 | app.use(middleware) |
| 路由模块 | app.use('/prefix', router) |
七、同类工具对比
| 特性 | Express | Fastify | Koa | NestJS |
|---|
| 性能 | 良好 | 极高 | 良好 | 良好 |
| 生态 | 最大 | 增长中 | 中等 | 大 |
| TypeScript | 手动 | 支持 | 手动 | 原生 |
| 学习曲线 | 低 | 低 | 低 | 中 |
| 适合场景 | 通用 | 高性能API | 极简 | 企业级 |
选型建议:通用 Node.js API 选 Express(生态最大);追求性能选 Fastify;企业级架构选 NestJS。
参考资料:Express 官网 | GitHub | npm