Home > Net >  Cannot set headers after they are sent to the client | Redirect causing issue?
Cannot set headers after they are sent to the client | Redirect causing issue?

Time:12-05

I am redirecting a successful login to my admin page but once my app.get route with express is initiated it is throwing me the "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client".. Any ideas why?

app.post('/login', function(request, response) {
    // Capture the input fields
    let username = request.body.username;
    let password = request.body.password;
  console.log(username);
  console.log(password);
    // Ensure the input fields exists and are not empty
    if (username && password) {
        // Execute SQL query that'll select the account from the database based on the specified username and password
        con.query('SELECT * FROM something WHERE user = ? AND password = ?', [username, password], function(error, results, fields) {
            // If there is an issue with the query, output the error
            if (error) throw error;
            // If the account exists
            if (results.length > 0) {
                // Authenticate the user
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('Admin'); //redirect to app.get('/Admin')
            } else {
                response.send('Incorrect Username and/or Password!');
            }           
            response.end();
        });
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
});
//LOGIN SESSION //
 
app.get('/Admin', function (req, res) {
  if (req.session.loggedin) {
    activeEmails()
    .then((result) =>{
    var email = result;
    console.log(email);
    res.render('Admin', { //error is coming here!
      email : email
    });
  });
    } else {
        // Not logged in
        res.redirect('login');
    }
    res.end();
  });

CodePudding user response:

res.end signals that all headers are sent and res.render sets headers. The order of execution in the request handler for the /Admin GET request is:

app.get('/Admin', function (req, res) {
  if (req.session.loggedin) {
    activeEmails().then((result) => {
      var email = result;
      console.log(email);
      res.render('Admin', { // second
        email : email
      });
    });
  } else {
    // Not logged in
    res.redirect('login');
  }
  res.end(); // first
});

First, res.end signals that all headers are sent and then, res.render tries to set headers. That causes the error. You must not call res.render after res.end.

I don't know why you call res.end in your code. You probably can remove all the calls. AFAIK, they are superfluous in your code.

  • Related