第 4 卷
- 应用级中间件(全局/路由前缀)
作用于整个应用或指定路由前缀,通过 app.use() 注册。
示例:
const express = require('express');
const app = express();
// 全局应用级中间件:记录所有请求日志 app.use((req, res, next) => {
console.log(`[${new Date().toLocaleString()}] ${req.method} ${req.url}`);
next(); // 调用下一个中间件 });
// 带路由前缀的应用级中间件:仅作用于/api开头的路由 app.use('/api', (req, res, next) => {
console.log("处理/api前缀的请求");
next();
});
// 路由处理 app.get('/api/user', (req, res) => {
res.send("用户列表");
});
app.listen(3000);
const router = express.Router();
// 路由级中间件:仅作用于当前router的所有路由 router.use((req, res, next) => {
console.log("路由级中间件处理");
next();
});
// 直接在路由中注册中间件(多个中间件可传入数组)
router.get('/detail', (req, res, next) => { req.userInfo = { id: 1, name: "张三" }; // 预处理数据
next();
}, (req, res) => { res.send(`用户信息:${JSON.stringify(req.userInfo)}`);
});
app.use('/user', router);
- 错误处理中间件
专门处理请求过程中的错误,格式为 (err, req, res, next) => { ... }(比普通中间件多一个 err 参数),需通过 app.use() 注册,且必须放在所有中间件和路由之后。
示例:
app.use((err, req, res, next) => { console.error("错误信息:", err.stack);
res.status(500).send("服务器内部错误");
});
// 触发错误:在中间件或路由中调用next(err)
app.get('/error', (req, res, next) => { const err = new Error("自定义错误");
next(err); // 交给错误处理中间件 });
域)。
示例:
// 内置中间件:解析JSON请求体 app.use(express.json());
// 内置中间件:解析x-www-form-urlencoded表单数据 app.use(express.urlencoded({ extended: false }));
// 第三方中间件:处理跨域 const cors = require('cors');
app.use(cors());
- Koa中间件的使用
Koa(基于ES6+)的中间件核心格式: (ctx, next) => { ... },其中 ctx 是上下文对象(封装了 req 和 res), next() 是返回Promise的函数,支持异步(async/await)。Koa中间
件采用“洋葱模型”执行,使用方式如下:
全站分卷索引 · 12 卷
- 1第 1 卷
- 2第 2 卷
- 四、Node.js中的非阻塞I/O(Non-blocking I/O)模型
- • 阻塞I/O:主线程发起I/O操作后,暂停执行所有代码,直到I/O操作完成(如传统的PHP文件读
- • 非阻塞I/O:主线程发起I/O操作后,立即返回一个状态(未完成),并继续执行后续代码;I/O操作
- • exports:是 module.exports 的一个引用(快捷方式),默认是一个空对象 {},只能通
- • module.exports:是模块的真正导出对象,Node.js最终导出的是 module.exports 的
- ◦ 若为相对路径( ./、 ../)或绝对路径,直接按路径查找对应
- ◦ 若为第三方模块(如 express),会在当前目录的 node_modules 文件夹中查找,若找不
- 3第 3 卷
- 4第 4 卷
- 5第 5 卷
- 6第 6 卷
- 7第 7 卷
- 8第 8 卷
- 9第 9 卷
- 10第 10 卷
- 11第 11 卷
- 12第 12 卷