lim
lim

Reputation: 51

How to Fix Node JS Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I want to make login using nodejs and mysql but i'am getting error like this:

undefined
undefined
SELECT * FROM user WHERE username = username AND password = password
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:455:11)

this is my code:

module.exports = (req, res) => {
    let login = "";
    res.send(htmlTemplate(login))

    var username = req.body.username;
    var password = req.body.password;
    var sql = `SELECT * FROM user WHERE username = username AND password = password`;

    console.log(username);
    console.log(password);
    console.log(sql);

    if(username && password) {
        connection.query('SELECT * FROM user WHERE username = username AND password = password', [username, password], function(error, results, fields){
        if(results.length > 0){
            req.session.loggedin = true;
            req.session.username = username;
            res.redirect('/dashboard');
        } else {
            res.send('Username and Password wrong!');
        }
        res.end();
        });
    } else {
        res.send('please enter Username and Password');
        res.end();
    }
}

can you help me solve this problem?

thank you.

Upvotes: 1

Views: 2781

Answers (2)

Ayush Gupta
Ayush Gupta

Reputation: 1

The problem is that you have already added res.send(htmlTemplate(login)) which ends the response for a request received on the endpoint. When the method flow continues after this statement it encounters res.redirect() or res.send() statements depending on the condition, and that is again used to send the response but the same has already been sent and it throws an error. To overcome this try separating the routes wherein you send the login page template and handle the logic behind logging in a user separately.

Upvotes: 0

BENARD Patrick
BENARD Patrick

Reputation: 31005

The res.send and res.json ends the request... so you don't have to include it after.

if(username && password) {
    connection.query('SELECT * FROM user WHERE username = username AND password = password', [username, password], function(error, results, fields){
    if(results.length > 0){
        req.session.loggedin = true;
        req.session.username = username;
        res.redirect('/dashboard');
    } else {
        res.send('Username and Password wrong!');
    }
    });
} else {
    res.send('please enter Username and Password');
}

Upvotes: 1

Related Questions