在函数内部包装passport.authenticate * callback *并不起作用

时间:2017-03-10 22:36:35

标签: passport.js koa

这与Wrapping passport.authenticate inside a function doesn't work密切相关。

我们使用Koa代替Express。因此,我将(req, res, next)替换为(ctx, next)。它对于初始的oauth2调用工作正常,但如果包含在函数中,则回调会抛出错误。

使用:

router.get('/auth/google/callback', passport.authenticate('google',
    {
        successRedirect: '/auth/success',
        failureRedirect: '/auth/fail',
        failureFlash: true,
    }));

失败:

const google_callback = (ctx, next) => {
    passport.authenticate('google',
        {
            successRedirect: '/auth/success',
            failureRedirect: '/auth/fail',
            failureFlash: true,
        }
    )(ctx, next);
};
router.get('/auth/google/callback', google_callback);

错误消息是:

Error: Can't set headers after they are sent.

1 个答案:

答案 0 :(得分:2)

This指出了我正确的方向。

<强>使用:

const google_callback = async (ctx, next) => {
    await passport.authenticate('google',
        {
            successRedirect: '/auth/success',
            failureRedirect: '/auth/fail',
            failureFlash: true,
        }
    )(ctx, next);
};