使用passport.js进行动态故障重定向



这是我的登录功能atm:

app.post("/login", passport.authenticate("local", {
    failureRedirect: "/login?error=1"
}), function (req, res) {
    res.redirect(req.body.url || "/");
});

我需要把req.body.url放在failureRedirect url中,所以它看起来应该是:

app.post("/login", passport.authenticate("local", {
    failureRedirect: "/login?error=1&url=" + (req.body.url || "/")
}), function (req, res) {
    res.redirect(req.body.url || "/");
});

它无法工作,因为req变量仅在post的回调内部初始化。。。我该怎么办?

您可以使用自定义回调动态生成回调url,因为req对象在其中可用。

也许有更干净的方法可以做到这一点,但这是任何简单的解决方法:

app.post(
    "/login",
    function (req, res, next) {
        const callback = passport.authenticate("local", {failureRedirect: "/login?error=1&url=" + (req.body.url || "/"});
        return callback(req, res, next);
    },
    function (req, res) {
        res.redirect(req.body.url || "/");
    }
);

不是立即使用调用passport.authenticate()返回的中间件,而是将其包装起来,以便可以使用req, res, next

最新更新