Chirag S Modi
Chirag S Modi

Reputation: 419

Can't set headers after they are sent in Express using Node

I am making template using express and ejs, res,end(). But didn't find any solution. I have tried my many things, like next()

Below is my code:

app.get('/', function (req, res, next) {
pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query( 'SELECT * FROM wp_posts WHERE post_name = "mainlogo"', function(err, mainmenu) {
    var data = JSON.stringify(mainmenu);

   return res.render('index', {items : data});
   res.end();

  });

  connection.query( 'SELECT * FROM wp_posts WHERE id = 14', function(err, homecontent) {
    var dataHome = JSON.stringify(homecontent);

   return res.render('index', {homeitem : dataHome});
   res.end();
    connection.release();
  });
});

});

This will give me error:

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

Can anyone help me?

Upvotes: 0

Views: 605

Answers (1)

pherris
pherris

Reputation: 17693

Each query is trying to send a full response back to the browser so the second one fails. Try something like this:

app.get('/', function (req, res, next) {
  pool.getConnection(function(err, connection) {
    // Use the connection
    connection.query( 'SELECT * FROM wp_posts WHERE post_name = "mainlogo"', function(err, mainmenu) {
      //got the results of the first query
      var posts = JSON.stringify(mainmenu);

      connection.query( 'SELECT * FROM wp_posts WHERE id = 14', function(err, homecontent) {
        //got the results of the second query
        var dataHome = JSON.stringify(homecontent);
        //return both
        return res.render('index', {homeitem : dataHome, items : data});
        //close connection
        res.end();
        //release connection
        connection.release();
      });
  });  
});

Upvotes: 1

Related Questions