简体   繁体   English

将额外的 arguments 传递给 function checkNotAuthenticated

[英]Passing extra arguments to function checkNotAuthenticated

I'm trying to write a function that checks whether the user is authenticated or not, and if they are, redirect them to a specific page, which is passed through the same function.我正在尝试编写一个 function 来检查用户是否经过身份验证,如果是,则将它们重定向到特定页面,该页面通过相同的 function 传递。 This is how I thought I could do it:这就是我认为我可以做到的方式:

function checkNotAuthenticated(req, res, next, redirect) {
    if (!req.isAuthenticated()) {
        return next()
    }
    res.redirect(redirect)
}

app.post("/login", checkNotAuthenticated("/account"), passport.authenticate('local', {
    successRedirect: "/account",
    failureRedirect: "/login",
    failureFlash: true
}))

However, this method does not pass the req , res and next arguments.但是,这种方法没有通过reqresnext arguments。 Those are only passed when I call the function without the parentheses ( checkNotAuthenticated ), being filled in for me.只有当我调用没有括号 ( checkNotAuthenticated ) 的 function 时,这些才通过,为我填写。 How can I run my own argument for the redirect through the same function?如何通过相同的 function 运行我自己的重定向参数? Or, is there a better way to achieve this?或者,有没有更好的方法来实现这一目标?

You can change the order of the parameters and use Function#bind .您可以更改参数的顺序并使用Function#bind

function checkNotAuthenticated(redirect, req, res, next) {
    if (!req.isAuthenticated()) {
        return next()
    }
    res.redirect(redirect)
}

app.post("/login", checkNotAuthenticated.bind(null, "/account"), passport.authenticate('local', {
    successRedirect: "/account",
    failureRedirect: "/login",
    failureFlash: true
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM