快速 - 条件路由

Express - Conditional Routing

本文关键字:路由 条件 快速      更新时间:2023-09-26

在我的website.com/v2/bridge/:locationId/process端点上,传入req.body如下所示:

{
  choice: 'a',
  data: [
    {
      ...
    },
    ...
  ]
}

我想根据req.body.choice的值访问特定路由。如果是req.body.choice === 'a',那么我想继续website.com/v2/bridge/:locationId/process/choiceA传递相同的req

我不知道我需要使用什么中间件来实现这一点。我不知道这是否可能。

我极其简化的路线:

// website.com/v2/bridge
const proc = require('./process');
router.use('/:locationId/process', proc);
module.exports = router;


// website.com/v2/bridge/56/process
router.use(function (req, res, next) {
  // ?????????????????????????
  next();
});
const choiceA = require('./choice-a');
const choiceB = require('./choice-b');
router.use('/choice-a', choiceA);
router.use('/choice-b', choiceB);
module.exports = router;


// website.com/v2/bridge/56/process/choice-a
router.post('/', function (req, res) {
  res.send('I got here.');
  return;
});
module.exports = router;

我需要包含哪些中间件函数才能有条件地路由我的请求?我试图避免使用if语句的巨型函数,该函数根据req.body.choice的值处理不同的事情。

这对

你来说会有点棘手...试一试

router.use(function (req, res, next) {
  req.path = "/" + "choice-"+req.body.choice
  req.url = "/" + "choice-"+req.body.choice
  next();
});

现在它会将请求执行到您想要的终点

作为寻找同一问题的答案的一部分,我遇到了这个问题,这个问题并没有通过弄乱 req.url 来安定我的心,所以这是我如何完成它的方式(我知道这是一个很长的延迟,但迟到总比没有好(:

当你在处理路由器时,你想做一个条件来决定是否使用,你可以用两种方式来完成(根据expressjs doc(,让我们通过例子来学习它们。

1. 在路线之间跳过

function skipThisRouteMiddleware (req, res, next) {
    if (true === isAmazingValidation) {
        return next('route');
    }
    return next();
}
router.get('/user/:id',
    skipThisRouteMiddleware,
    getUserV1 // TBD - your old route
)
router.get('/user/:id',
    getUserV2 // TBD - your new route
)

在上面的情况下,当你有两个路由,并且你想有条件地选择其中一个时,可以通过指定一个中间件来完成,该中间件只对第一个路由进行验证,并在需要时触发跳到下一个匹配路由next('route'),请注意,您必须指定 METHOD,而不是通常app.use()

2. 在路由器之间跳跃

// routers/index.js
const mainRouter = express.Router();
mainRouter.use(oldRouter);
mainRouter.use(newRouter);

// routers/old.js
const oldRouter = express.Router();
function canUpgradeToNewRouter (req, res, next) {
    if (true === isAmazingValidation) {
        return next('router'); // now it's 'router' and not 'route'
    }
    return next();
}
oldRouter.use(canUpgradeToNewRouter);

// routers/new.js
const newRouter = express.Router();
newRouter.use(...);

在这种情况下,您有两个不同的路由器,并且您希望有条件地选择其中一个。 对于这种情况,您必须创建一个父路由器(mainRouter(和两个嵌套路由器(oldRouter,newRouter(。这里的诀窍是oldRouter尝试运行中间件验证,该验证尝试将请求者"升级"到新的闪亮路由器,如果条件为真,它将跳过整个oldRouter,并将棒传递给父路由器mainRouter以继续匹配此请求的路由(魔术 - next('router')(, 最终选择即将到来的newRouter

在这两种方法中,我们让第一条路线来制定逻辑并在自己和其他路线之间进行选择,这是一种不同的感知(有点(