首页 > 解决方案 > 在自定义函数中链接中间件函数

问题描述

我知道我可以在传递路径后链接中间件函数

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 路由时,我没有得到任何响应

无法得到任何回应

所以它会永远加载。有没有办法将这些中间件函数链接到另一个函数中?

标签: javascriptnode.jsexpress

解决方案


除了返回一个数组之外,您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);

推荐阅读