【问题标题】:passport.js throws Error: Can't set headers after they are sentpassport.js 抛出错误:发送后无法设置标题
【发布时间】:2020-05-30 18:00:18
【问题描述】:

我已阅读其他解决方案,但这些对我不起作用。

[1]这里讲的是使用else,我已经用过了。
[2] 另一个人谈到使用returndone 这似乎不合逻辑,因为文档没有提到使用return

无论用户是否登录,我都需要加载一个页面。如果用户未登录,我必须显示登录按钮,否则显示注销按钮。

这是发生错误的路径:

app.get('/', (req, res, next) => {
    if(req.query.code || req.cookie) { //either first time authenticating or already a user
        passport.authenticate('google')(req, res, next)
    }
    res.render('index', { user: req.user });
})

这是我在用户点击登录时点击的路线:

app.get('/google', passport.authenticate('google', {
    scope: ['profile', 'email']
}));

这是我的护照策略设置:

passport.use(
    new GoogleStrategy({
        callbackURL: `${process.env.address}`,
        clientID: `${process.env.GOOGLE_SSO_CLIENT_ID}`,
        clientSecret: `${process.env.GOOGLE_SSO_CLIENT_SECRET}`,

    }, (accessToken, refreshToken, profile, done) => {

        if(accessToken) {
            User.findOne({email: profile.email}).then((currentUser) => {

                if(currentUser){ // already exists
                    console.log('user is: ', currentUser);
                    done(null, currentUser)
                    // do something
                } else { // if not, create user in our db
                    new User({
                        email: profile.email,
                        joinDate: Date.now(),
                        username: 'random'
                    }).save().then((newUser) => {
                        console.log('created new user: ', newUser);
                        done(null, newUser)
                        // do something
                    });
                }
            });
        } else {
            done(null, null)
        }
    })
)

问题可能是我试图点击

【问题讨论】:

    标签: node.js express passport.js


    【解决方案1】:

    我认为这对你有用吗?

    app.get('/', (req, res, next) => {
        if(req.query.code || req.cookie) { 
            passport.authenticate('google', function(req, res, next) {
               res.render('index', { user: req.user });
            });
        } else {
            res.render('index');
        }
    })
    

    【讨论】:

    • 为什么要使用自定义回调?此外,自定义回调的方法签名似乎涉及 err, user, info 而不是 req, res, next passportjs.org/docs/downloads/html
    • 看看页面的最后部分pasport/
    • 如果您在谈论方法,我认为(req, res) 用于app.get() 而不是。如果您说的是自定义回调,抱歉我没看懂,您能详细说明一下吗?
    • 另外,为什么要添加重复的else?之前也想过,结果没变。
    猜你喜欢
    • 2017-05-31
    • 2019-07-17
    • 2015-11-13
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多