无法在Node js和sqlite3中设置标头

时间:2016-10-14 16:10:38

标签: json node.js express sqlite

您好我在这个错误中挣扎了很长一段时间,甚至我发现许多类似的问题我无法解决它。如果您可以查看我的代码并给我一个建议,我会非常感激!

//Register User
router.post('/register', function(req,res) {
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;


//Validation 
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);



var errors = req.validationErrors();


if (errors){
    res.render('register', {
        errors:errors
    });

} else {
    var stmt = db.prepare("INSERT INTO users ( id, username, email, password, salt) VALUES (NULL, ?, ?, ?, ?)");
    stmt.run([ username, email, hashPassword(password,'salt'), 'salt'],function(error){
                    if(error) {
                    res.render('register', {
                    error:'Email is already taken'
                        });
                    };
                }).finalize();
        req.flash('success_msg','You are registered and can now login');
        res.redirect('/users/login');
}
 });

我认为问题是最后一个res.redirect('/users/login');,我也尝试使用return语句,但即便如此,它仍然会抛出这个错误:

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at ServerResponse.header (/Users/SGI02144/IdeaProjects/login/node_modules/express/lib/response.js:719:10)
at ServerResponse.send (/Users/SGI02144/IdeaProjects/login/node_modules/express/lib/response.js:164:12)
at done (/Users/SGI02144/IdeaProjects/login/node_modules/express/lib/response.js:956:10)
at Immediate.<anonymous> (/Users/SGI02144/IdeaProjects/login/node_modules/express-handlebars/lib/utils.js:26:13)
at runCallback (timers.js:574:20)
at tryOnImmediate (timers.js:554:5)
at processImmediate [as _immediateCallback] (timers.js:533:5)

1 个答案:

答案 0 :(得分:0)

问题是res.render('register'...正在尝试在res.redirect('/user/login') https://expressjs.com/en/4x/api.html#res.render之后发送有关错误https://expressjs.com/en/4x/api.html#res.redirect的回复。

我建议推杆 req.flash('success_msg','You are registered and can now login'); res.redirect('/users/login');

finalizefinalize.then()

的回调中