← 返回目录

第 4 卷

第 4 / 12 卷日期:

  1. 应用级中间件(全局/路由前缀)

作用于整个应用或指定路由前缀,通过 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);

  1. 错误处理中间件

专门处理请求过程中的错误,格式为 (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());

  1. Koa中间件的使用

Koa(基于ES6+)的中间件核心格式: (ctx, next) => { ... },其中 ctx 是上下文对象(封装了 req 和 res), next() 是返回Promise的函数,支持异步(async/await)。Koa中间

件采用“洋葱模型”执行,使用方式如下:

全站分卷索引 · 12 卷
  1. 1第 1 卷
  2. 2第 2 卷
  3. 3第 3 卷
  4. 4第 4 卷
  5. 5第 5 卷
  6. 6第 6 卷
  7. 7第 7 卷
  8. 8第 8 卷
  9. 9第 9 卷
  10. 10第 10 卷
  11. 11第 11 卷
  12. 12第 12 卷