Javascript 自定义函数中的链中间件函数
我知道我可以在通过如下路径后链接中间件功能Javascript 自定义函数中的链中间件函数,javascript,node.js,express,Javascript,Node.js,Express,我知道我可以在通过如下路径后链接中间件功能 const express = require('express'); const router = express.Router(); router.post('/', middlewareFunction1, middlewareFunction2, controllerFunction); module.exports = router; 我想知道是否可以只调用一个函数(称为网关) 这个函数能够链接所有这些方法 const controller
const express = require('express');
const router = express.Router();
router.post('/', middlewareFunction1, middlewareFunction2, controllerFunction);
module.exports = router;
我想知道是否可以只调用一个函数(称为网关)
这个函数能够链接所有这些方法
const controller = require('../controllers/controller');
function gatewayFunction1(request, response, next) {
// validate route
// do other middleware stuff
// call controller.function1
}
module.exports = {
gatewayFunction1,
};
我为什么要这么做?我正在考虑将中间件逻辑与路由分离。这个网关应该在路由之后和调用路由器之前执行
我试图返回一个函数数组(示例代码)
但是当我调用这个api路由时,我没有得到响应
没有得到任何回应
所以它一直在加载。有没有办法将这些中间件函数链接到另一个函数中?中间件应该是一个函数,您将返回一个数组。如果不调用下一个函数,它将被卡住。我不喜欢将它们组合在一起的整个想法,但我认为最好的方法是将所有中间件函数导入到一个函数中,并单独调用它们,然后将该函数用作组合的中间件。您的
网关函数1
除了返回数组外,什么都不做。
只需使用路由器
const express = require('express');
const gatewayFunction1 = express.Router();
gatewayFunction1.use(middlewareFunction1, middlewareFunction2, controllerFunction);
module.exports = gatewayFunction1;
然后
您是否尝试过router.post(“/”,…网关功能1)?扩展数组?很抱歉,我收到一个
TypeError:Found non callable@@iterator
错误
function gatewayFunction1(request, response, next) {
return [(request, response, next) => {
console.log('called middleware 1');
next();
}, (request, response, next) => {
console.log('called middleware 2');
next();
}, (request, response, next) => {
response.status(200).json({
message: 'that worked',
});
}];
}
const express = require('express');
const gatewayFunction1 = express.Router();
gatewayFunction1.use(middlewareFunction1, middlewareFunction2, controllerFunction);
module.exports = gatewayFunction1;
const gatewayFunction1 = require('...'); // where you define gatewayFunction1
router.post('/', gatewayFunction1);