Passport Cant在发送后设置标头

时间:2016-11-24 10:43:49

标签: javascript node.js express

你好我有节点/护照的问题,我已经检查了Stackoverflow上的答案,但没有什么对我有用..

所以我试图使用护照,但我有这个错误:

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

这是我的策略:

passport.use('42', new FortyTwoStrategy({
    clientID: configAuth.schoolAuth.clientId,
    clientSecret: configAuth.schoolAuth.clientSecret,
    callbackURL: configAuth.schoolAuth.callbackURL,
}, (accessToken, refreshToken, profile, done) => {
    process.nextTick(() => {
        console.log(1);
            console.log(2);

            User.findOne({ $and: [{ username: profile.username }, { provider: '42' }] }, (err, user) => {
                if (err) return done(err, { status: false, details: 'Cant connect to db' });
                if (!user) {
                    const newUser = new User({
                        id: profile.id,
                        username: profile.username,
                        mail: profile.emails[0].value,
                        image: profile.photos[0].value,
                        provider: '42',
                    });
                    newUser.save((erro) => {
                        if (erro) return done(erro);
                        return done(null, user, { status: true, details: 'success' });
                    });
                } else {
                return done(null, user, { status: true, details: 'success' });
            }
            });
        return (false);
    });
}));

我的路线:

app.get('/api/user/auth/42', passport.authenticate('42'));

    app.get('/api/user/auth/42/callback', userFonc.schoolLogin);

和我的回调函数:

schoolLogin: (req, res, next) => {
            passport.authenticate('42', (err, user) => {
                if (err) return res.send(err);
                if (!user) {
                    return res.send({ status: false, details: 'error occured' });
                }
                const token = jwt.sign({ _id: user._id, username: user.username }, cfg.jwtSecret);
                res.set('Access-Control-Expose-Headers', 'x-access-token');
                res.set('x-access-token', token);
                res.send({ status: 'success', user });
                return res.send(user);
            })(req, res, next);
        },

如果有人能解释我为什么会有这个错误以及如何删除它...因为我认为我的回归应该像那样......

谢谢

2 个答案:

答案 0 :(得分:0)

您正在呼叫res.send两次。这就是错误的原因。

res.send发送数据并关闭与客户端的连接。

您只能使用res.send s

中的一个
res.send({ status: 'success', user });  
return res.send(user);

答案 1 :(得分:0)

"发送标题后不能发送标题"当您多次尝试向用户发送响应时,会发生语句。

错误通过跳过第二次发送响应头来指定这一点。

在:

res.send({ status: 'success', user });  
return res.send(user);

取出一个res.send语句,具体取决于您的应用程序的需要。