express的中间件,全局中间件,路由中间件,静态资源中间件以及使用注意事项 , 获取请求体数据
Express 中间件系统 的详细讲解,包括全局中间件、路由中间件、静态资源中间件、请求体解析中间件,以及使用注意事项👇
🌐 一、什么是中间件(Middleware)?
中间件是 函数,在请求到达路由处理器之前被调用,用于拦截、修改请求或响应,或者终止请求处理流程。
中间件函数格式:
(req, res, next) => { /* your logic */ }
调用 next()
表示继续传递请求给下一个中间件;否则请求会被“卡住”。
📌 二、全局中间件(应用级)
示例 1:日志中间件(所有请求都会执行)
app.use((req, res, next) => {console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);next(); // 继续执行下一个中间件
});
🚏 三、路由中间件(局部)
只对特定路由生效的中间件:
const checkAuth = (req, res, next) => {if (req.query.token === '123') {next();} else {res.status(401).send('Unauthorized');}
};app.get('/secure', checkAuth, (req, res) => {res.send('Access granted!');
});
📁 四、静态资源中间件
内置中间件 express.static()
用于托管静态文件(HTML、CSS、JS、图片等):
app.use(express.static('public')); // 访问 public 文件夹// 假设 public 中有 index.html,可以直接通过 http://localhost:3000/index.html 访问
🧾 五、获取请求体数据的中间件
1. 解析 JSON 格式
app.use(express.json());
2. 解析表单格式(x-www-form-urlencoded)
app.use(express.urlencoded({ extended: true }));
示例 POST 路由:
app.post('/login', (req, res) => {const { username, password } = req.body;res.send(`用户名:${username}, 密码:${password}`);
});
⚠️ 六、使用注意事项
注意事项 | 说明 |
---|---|
中间件顺序 | 中间件是按顺序执行的,先定义的先执行 |
next() 必须调用 | 否则请求会卡住,不继续执行后续中间件或路由 |
错误处理中间件 | 中间件中捕获错误时要调用 next(err) ,Express 会自动进入错误处理中间件 |
静态中间件要放前面 | 否则可能被其他中间件或路由拦截 |
不要滥用全局中间件 | 建议用局部中间件提高性能与可维护性 |
🎁 七、完整示例
const express = require('express');
const app = express();
const port = 3000;// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));// 全局日志中间件
app.use((req, res, next) => {console.log(`[LOG] ${req.method} ${req.url}`);next();
});// 路由中间件示例
const auth = (req, res, next) => {if (req.query.token === '123') next();else res.status(401).send('未授权');
};app.get('/public-info', (req, res) => res.send('Everyone can see this'));app.get('/private-info', auth, (req, res) => res.send('This is protected'));app.post('/form', (req, res) => {res.send(req.body);
});app.listen(port, () => {console.log(`App running at http://localhost:${port}`);
});