javascript - 在自定义函数中链接中间件函数
问题描述
我知道我可以在传递路径后链接中间件函数
const express = require('express');
const router = express.Router();
router.post('/', middlewareFunction1, middlewareFunction2, controllerFunction);
module.exports = router;
我想知道是否可以只调用一个函数(称为网关)
router.post('/', gatewayFunction1);
这个函数能够链接所有这些方法
const controller = require('../controllers/controller');
function gatewayFunction1(request, response, next) {
// validate route
// do other middleware stuff
// call controller.function1
}
module.exports = {
gatewayFunction1,
};
我为什么要这么做?我正在考虑将中间件逻辑与路由分开。这个网关应该在路由之后和调用路由器之前执行。
我试图返回一个函数数组(示例代码)
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',
});
}];
}
但是当我调用这个 api 路由时,我没有得到任何响应
无法得到任何回应
所以它会永远加载。有没有办法将这些中间件函数链接到另一个函数中?
解决方案
除了返回一个数组之外,您gatewayFunction1
什么都不做。只需使用router
.
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);
推荐阅读
- angular - 角,量角器,黄瓜问题
- mysql - 在我的 sql 中加入两个表不返回结果集
- powershell - Powershell:通过将脚本指向功能列表来添加 WindowsFeature
- java - Firebase Auth:来自不同活动的getCurrentUser?
- c++ - 函数未返回所需的字符串
- symbolic-math - 基于加法(+)运算符 MAPLE 创建子表达式
- scala - 无法将 scala 对象转换为 spark 数据帧
- php - 使用 PHP 将图像插入 docx 文件的最简单方法
- actions-on-google - 为谷歌操作的函数中的值创建实体和训练短语
- android - 动态更改 ImageView 大小?