gpt4 book ai didi

javascript - 有什么方法可以在 express 中使用 next() 有条件地跳过中间件?

转载 作者:行者123 更新时间:2023-11-29 21:40:21 25 4
gpt4 key购买 nike

例如-

//Functions

var validationCheck = function(req, res, next){
if(req.session.userId && req.session.token)
next('validationCatch') //Is this possible to skip middleware if not needed?
else
next()
}

var getUserId = function(req, res, next){
req.session.userId = DB.getUserId
next()
}

var getToken = function(req, res, next){
req.session.token = DB.getToken
next()
}

//a catcher function to direct to next function depending on route
var validationCatch = function(req, res, next){
next()
}

//Routes

app.get(api + '/feature1', validationCheck, getUserId, getToken, validationCatch, feature1)
app.get(api + '/feature2', validationCheck, getUserId, getToken, validationCatch, feature2)

我的目标是如果信息已经从以前的路由中缓存,则跳过不必要的中间件。所以在上面的例子中,如果 feature1 已经被调用,feature2 就不需要输入 getUserIdgetToken ,从而使响应更快。

如果不可能,请说明一个更有效的架构来处理重复的验证过程。谢谢

最佳答案

与其直接注册回调,不如在需要时在 validationCheck 中调用它们。这是一个使用 getUserId 的简单示例:

var validationCheck = function(req, res, next){
if(req.session.userId)
next()
else {
getUserId(req, res, function(err){
next(err)
})
}
}

关于javascript - 有什么方法可以在 express 中使用 next() 有条件地跳过中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com