0
votes

I've try a lot's of different solution on stackoverflow about this but. But they didn't work.

It raise this error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) at ServerResponse.header (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/response.js:771:10) at ServerResponse.location (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/response.js:888:15) at ServerResponse.redirect (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/response.js:926:18) at Statement. (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/app.js:135:28) --> in Database#each("SELECT * FROM users WHERE email='yyyy@yyyy'", [Function]) at /mnt/c/Users/Lucas-PC/Desktop/OnlineChat/app.js:133:16 at Layer.handle [as handle_request] (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/layer.js:95:5) at next (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/layer.js:95:5) at /mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/index.js:335:12) at next (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/index.js:275:10) at /mnt/c/Users/Lucas-PC/Desktop/OnlineChat/app.js:70:5 { code: 'ERR_HTTP_HEADERS_SENT', __augmented: true }

Here is my code:


const redirectLogin = (req, res, next) => {
    if (!req.session.userId){
        res.redirect('/login');
    }else {
        next();
    }
}

const redirectHome = (req, res, next) => {
    if (req.session.userId){
        res.redirect('/dashboard');
    }else {
        next();
    }
}

app.post('/login', redirectHome, (req, res) => {
    reloadUsers(users);
    const { email, password } = req.body;
    if (email && password) {
        const user = users.find(user => user.email === email && user.password === password) // TODO: hash password
        if (user){
            console.log(user.id);
            req.session.userId = user.id;
            res.redirect('/dashboard');
            return;
        }
    }
    res.redirect('/')
})


app.post('/register', redirectHome, (req, res) => {
    const { name, job, email, password } = req.body;

    if (name && job && email && password){ // TODO: validation more complex
        const exists = users.some(user => user.name === name && user.email === email);

        if(!exists){
            let infos = [name, email, job, password];
            let placeholders = infos.map((info) => '?').join(',');
            let sql = 'INSERT INTO users(name, email, job, password) VALUES('+ placeholders +')';
            db.run(sql, infos);
            console.log('email: '+req.body.email);
            db.each("SELECT * FROM users WHERE email='"+req.body.email+"'", (err, row) => {
                req.session.userId = row.id;
            })
            return res.redirect('/dashboard');
        }
    }

    res.redirect('/');
})

app.post('/logout', redirectLogin, (req, res) => {
    reloadUsers(users);
    req.session.destroy(err => {
        if (err){
            return res.redirect('/dashboard');
        }
        res.clearCookie(SESS_NAME);
        res.redirect('/login');
    });
})

I think the error come from the app.post('/login') and app.post('/register') on the res.redirect('/dashboard')

1

1 Answers

0
votes

Under your /register router, you are trying to set the request after response is sent.

db.each("SELECT * FROM users WHERE email='"+req.body.email+"'", (err, row) => {
    req.session.userId = row.id;
})
return res.redirect('/dashboard');

db.each() is an asynchronous function so you would have to handle response within the function.

db.each("SELECT * FROM users WHERE email='"+req.body.email+"'", (err, row) => {
    req.session.userId = row.id;
    return res.redirect('/dashboard');
})

SOME TIPS: Also try to escape your strings when you are constructing SQL statements to avoid SQL injections.