如何有条件地调用路由级中间件?

How to call router level middleware conditionally?

我有两个函数来验证请求正文,validation1validation2。 现在我的任务是,在解析传入的请求正文之后, 如果用户角色是 premium user,我需要使用 validation1 验证数据,否则我将使用 validation2.

验证数据

我试过像下面这样解决,但无济于事。出于某种原因,验证中间件没有被调用。

const express = require('express');
const router = express.Router();
   
const { userController } = require('./controllers');

router.route('/check').post(
  (req, res, next) => {
    if (req.role === 'premium user') {
      validation1(someInformation);
    } else {
      validation2(someInformation);
    }
    next();
  },
  userController.check
);


const validation1 = (someInformation) => (req, res, next) => {
  // codes
  return next();
}

const validation2 = (someInformation) => (req, res, next) => {
  // codes
  return next();
}

如有任何帮助,我们将不胜感激。提前致谢。

你应该传递回调函数next来验证函数。

也像下面的代码一样更改您的验证函数:

const express = require('express');
const router = express.Router();
   
const { userController } = require('./controllers');

router.route('/check').post(
  (req, res, next) => {
    if (req.role === 'premium user') {
      validation1(req, res, next);
    } else {
      validation2(req, res, next);
    }
  },
  userController.check
);


const validation1 = (req, res, next) => {
  // codes
  return next();
}

const validation2 = (req, res, next) => {
  // codes
  return next();
}