Node.js多中间件导出模式



我使用Nodejs、Expressjs和
我不知道中间件中的next((到底是如何工作的

中间件/myMiddleware.js

const { Router } = require('express');
const router = Router();
module.exports = {
mA: router.use((req, res, next) => {
console.log('a');
next();
}),
mB: router.use((req, res, next) => {
console.log('b');
next();
}),
};

routes/myRoute.js

const { mA, mB } = require('../middlewares/myMiddleware');
router.get('/welcome'
, mA
,(req, res) => res.render('welcome'));
router.get('/welcome2'
, mB
,(req, res) => res.render('welcome2'));
module.exports = router;

这应该像这样工作
welcome2->log b

但它有效
welcome2->loga,logb
为什么
我该如何修复?这个设计不好吗?

问题是router.use((req, res, next) => {...})强制将中间件应用于整个路由器。

这里没有正确定义中间件。如手册所述,

中间件函数是可以访问请求对象(req(、响应对象(res(和应用程序请求-响应周期中的下一个中间件函数的函数。下一个中间件函数通常由一个名为next的变量表示。

mAmB是已经应用了中间件的路由器实例。

它们应该是:

module.exports = {
mA: (req, res, next) => {
console.log('a');
next();
},
mB: (req, res, next) => {
console.log('b');
next();
},
};

next((是Express框架公开的一个函数。它不是Nodejs的一部分,而是Expressjs的组成部分。根据明示文件"中间件函数是可以访问请求对象(req(、响应对象(res(和应用程序请求-响应周期中的下一个函数的函数。下一个功能是Express路由器中的一个函数,当被调用时,它执行当前中间件之后的中间件。">

希望这对你有所帮助。

感谢

最新更新