0

目前,我为更多的誓言提供者提供了以下代码:

// facebook
router.get("/facebook", passport.authenticate("facebook", { scope: ["email"] }));
router.get("/facebook/callback", passport.authenticate("facebook"), (req, res) => {
    console.log(chalk.blue("went into facebook callback"));
    res.redirect("http://localhost:3000/profile");
});

// github
router.get("/github", passport.authenticate("github"));
router.get("/github/callback", passport.authenticate("github"), (req, res) => {
    console.log(chalk.blue("went into github callback"));
    res.redirect("http://localhost:3000/profile");
});

有没有办法将其统一为抽象路线?即类似的东西

// github
router.get("/:provider", passport.authenticate(:provider));
router.get("/:provider/callback", passport.authenticate(:provider), (req, res) => {
    console.log(chalk.blue("went into {:provider} callback"));
    res.redirect("http://localhost:3000/profile");
});

更新: 以下代码可以满足我的要求。感谢@Usman Abdur Rehman。

function callbackDistributer(req, res, next) {
    console.log(req.params);
    global.provider = req.params.provider;
    next();
}

router.get(
    "/:provider/callback",
    callbackDistributer,
    (req, res, next) => {
        passport.authenticate(global.provider)(req, res, next);
    },
    (req, res) => {
        console.log(chalk.red("went into: " + global.provider));
        res.redirect("http://localhost:3000/profile");
    }
);
4

1 回答 1

1

在 passport.authenticate 中间件之前有一个中间件功能

function ownMiddleware(req,res,next){
    global.provider = req.params.provider
    next()
}

然后在路由处理程序中使用它作为

router.get("/:provider/callback", ownMiddleware ,passport.authenticate(global.provider), (req, res) => {
    console.log(chalk.blue("went into {:provider} callback"));
    res.redirect("http://localhost:3000/profile");
});

我认为它应该工作

于 2019-12-22T11:13:58.683 回答