express - 过滤中间件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
解决方案
我想你想做这样的事情:
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);
}
推荐阅读
- reactjs - 为什么 Stripe.js 没有使用 react-stripe-elements 在 React 中加载?
- android - 底部视图不在屏幕上,我该如何解决
- prolog - Prolog - 以列表为条件过滤列表
- python-3.x - 在事件循环中等待未来/协程;外部协程
- opengl - 从 gl_FragColor 切换到“out”值没有渲染
- javascript - 设置 useState 对象值时使用 prop 值
- unix - 在 Unix 中粘贴具有不等行和多列的文件
- c# - JsonConvert.DeserializeObject 未按预期从 JSON 转换响应对象
- python - 自定义 Kite python 库
- java - 使用 java.time.Clock.offset 以任意开始时间递增时间