使用Node在Express中发送标头后,无法设置标头

时间:2015-06-03 18:26:07

标签: node.js express ejs

我使用express和ejs,res,end()制作模板。但没有找到任何解决方案。我尝试了很多东西,比如next()

以下是我的代码:

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();
  });
});

});

这会给我错误:

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

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

每个查询都试图将完整的响应发送回浏览器,因此第二个查询失败。尝试这样的事情:

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();
      });
  });  
});