0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Chirag S Modi
  • 409
  • 7
  • 22

1 Answers1

1

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();
      });
  });  
});
pherris
  • 17,195
  • 8
  • 42
  • 58
  • is there any other way to do this? – Chirag S Modi Jun 03 '15 at 18:55
  • I would probably use RSVP (https://github.com/tildeio/rsvp.js/) with a promise for each query. Then use the .all(...) method to wait for each to complete/fail. Otherwise you might want to check out other SO questions on similar topics: http://stackoverflow.com/questions/6597493/synchronous-database-queries-with-node-js – pherris Jun 03 '15 at 19:00