Node系列 · Express:常用的中间件
Express 的核心能力只有路由和中间件机制------所有"开箱即用"的功能都是中间件实现的。本章盘点最常用的几个内置和第三方中间件。
一、内置中间件(Express 自带)
1.1 express.static:静态资源服务
把指定目录的文件对外暴露成 HTTP 静态资源:
javascript:static-middleware.js
app.use(express.static('public'));
app.use(express.static('files'));
// 多个目录按顺序查找
text:public/
├── index.html
├── style.css
└── images/logo.png
bash
$ curl http://localhost:3000/index.html
$ curl http://localhost:3000/style.css
$ curl http://localhost:3000/images/logo.png
::: tip
生产环境用 Nginx / CDN 提供静态资源 ------Express 静态中间件适合本地开发和内部工具,高并发场景 Nginx 性能更好。
:::
虚拟路径前缀:
javascript:static-virtual.js
app.use('/static', express.static('public'));
// 访问 /static/style.css → public/style.css
1.2 express.urlencoded:解析表单 POST
javascript:urlencoded.js
app.use(express.urlencoded({ extended: false }));
// 接收表单提交:name=Alice&age=25
app.post('/login', (req, res) => {
console.log(req.body); // { name: 'Alice', age: '25' }
res.send('ok');
});
extended: false 用 querystring 库解析(只支持字符串);extended: true 用 qs(支持嵌套对象)。
1.3 express.json:解析 JSON POST
javascript:json-parser.js
app.use(express.json({ limit: '1mb' }));
// 接收 JSON:{"name":"Alice","age":25}
app.post('/api/users', (req, res) => {
console.log(req.body); // { name: 'Alice', age: 25 }
res.json({ id: 1 });
});
| 参数 | 默认值 | 说明 |
|---|---|---|
limit |
'100kb' |
请求体最大体积;防 OOM |
strict |
true |
只接受对象 / 数组(不接收字符串 / null) |
type |
'application/json' |
Content-Type 匹配规则 |
二、第三方中间件
2.1 morgan:HTTP 请求日志
bash
npm install morgan
javascript:morgan.js
const morgan = require('morgan');
app.use(morgan('dev')); // 开发:彩色简洁
app.use(morgan('combined')); // 生产:Apache 风格详细
输出示例:
:method :url :status :res[content-length] - :response-time ms
GET /api/users 200 42 - 12 ms
| 格式 | 用途 |
|---|---|
combined |
生产(详细) |
common |
生产(中等) |
dev |
开发(彩色) |
short |
最简洁 |
tiny |
比 short 更短 |
写文件:
javascript:morgan-file.js
const fs = require('fs');
const accessLog = fs.createWriteStream('access.log', { flags: 'a' });
app.use(morgan('combined', { stream: accessLog }));
2.2 cors:跨域
bash
npm install cors
javascript:cors.js
const cors = require('cors');
// 允许所有跨域(开发期)
app.use(cors());
// 只允许特定源
app.use(cors({
origin: ['https://example.com', 'https://admin.example.com'],
credentials: true, // 允许携带 Cookie
}));
详见 第 11 章 cors 中间件。
2.3 helmet:安全头
bash
npm install helmet
javascript:helmet.js
const helmet = require('helmet');
app.use(helmet());
一行给响应加上 11 个安全相关的 HTTP 头:
X-Content-Type-Options: nosniff(防 MIME 嗅探)X-Frame-Options: SAMEORIGIN(防点击劫持)Strict-Transport-Security(强制 HTTPS)X-XSS-Protection(XSS 防护)- 等
::: tip
所有生产 Express 项目都建议加 helmet() ------一行代码解决大量安全问题。
:::
2.4 compression:Gzip 压缩
bash
npm install compression
javascript:compression.js
const compression = require('compression');
app.use(compression());
自动给响应体做 gzip 压缩------文本响应(HTML / JSON)大小可减少 60-80%。
2.5 cookie-parser:解析 Cookie
bash
npm install cookie-parser
javascript:cookie-parser.js
const cookieParser = require('cookie-parser');
app.use(cookieParser('my-secret'));
app.get('/set', (req, res) => {
res.cookie('token', 'abc123', { httpOnly: true });
res.send('ok');
});
app.get('/get', (req, res) => {
console.log(req.cookies); // { token: 'abc123' }
res.json(req.cookies);
});
2.6 multer:文件上传
bash
npm install multer
javascript:multer.js
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/api/upload', upload.single('avatar'), (req, res) => {
console.log(req.file);
// {
// fieldname: 'avatar',
// originalname: 'photo.jpg',
// encoding: '7bit',
// mimetype: 'image/jpeg',
// destination: 'uploads/',
// filename: 'xxx-xxxx.jpg',
// path: 'uploads/xxx-xxxx.jpg',
// size: 12345
// }
res.json({ url: `/uploads/${req.file.filename}` });
});
2.7 express-rate-limit:限流
bash
npm install express-rate-limit
javascript:rate-limit.js
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 分钟
max: 100, // 最多 100 次请求
message: '请求过于频繁,请稍后再试',
});
app.use('/api', limiter);
防爬虫、防爆破登录接口。
三、中间件选型速查
| 场景 | 中间件 |
|---|---|
| 静态资源 | express.static |
| 解析 JSON body | express.json |
| 解析表单 body | express.urlencoded |
| HTTP 日志 | morgan |
| 跨域 | cors |
| 安全头 | helmet |
| Gzip | compression |
| Cookie | cookie-parser |
| 文件上传 | multer |
| 限流 | express-rate-limit |
| Session | express-session(详见 session) |
| JWT | jsonwebtoken(详见 JWT) |
四、最佳实践
| 场景 | 推荐 |
|---|---|
| 生产环境必须 | helmet + compression + cors |
| 开发环境 | morgan('dev') |
| body 解析 | express.json + express.urlencoded |
| 静态资源 | 开发用内置;生产用 Nginx |
| 限流 | 公开接口必加(防爆破、防爬虫) |
| 文件上传 | 限制大小(如 limits: { fileSize: 5 * 1024 * 1024 }) |
五、小结
express.static提供静态资源服务;express.json/express.urlencoded解析请求体- 第三方必备三件套:
morgan(日志)+helmet(安全)+compression(压缩) - 文件上传用
multer,限流用express-rate-limit - 生产环境最少要:
helmet+compression+cors+morgan+ body 解析器 - 中间件按
app.use()顺序执行;通用中间件在前,业务路由在后