首页 > 解决方案 > 过滤中间件js

问题描述

我需要在我的 MVC js 项目中添加一个中间件过滤器,它将控制权转移到控制器,如果过滤器条件为假,控制器将执行一些操作,如果条件为真,则呈现特殊页面(但不将控制权交给控制器) . 它必须是在控制器逻辑之前执行的中间件,并且它不应该是控制器中的函数。

在这里,我有一条路线,现在只在控制器中执行下载方法。

if (config.common.zoneName === 'main') {
router.get('/book/:itemid', new 
DownloadController(ResourceRepo).download);
}

我需要在那里添加一些逻辑,例如

if (itemid > 10){
//render some special page
} 
//execute download method on the same controller
}   

在实际任务中,情况非常复杂(例如获取请求 IP 并检查具有相同 IP 的数据库中的字段)。所以条件不是内联函数,而是一些复杂的方法。我怎样才能使用 expressjs 中间件做到这一点?非常感谢:3

标签: expressmodel-view-controllermiddleware

解决方案


我想你想做这样的事情:

if (config.common.zoneName === 'main') {
  router.get('/book/:itemid', 
    (req, res, next) => {
      if (req.params.itemid > 10){
        //render some special page
      } 
      //execute download method on the same controller
    },
    new DownloadController(ResourceRepo).download);
}

推荐阅读