Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working with Node.js (express) and MySQL and I have had problems trying to make several queries in the same route. The error it throws is:

Can't set headers after they are sent.

And my code is this:

router.post('/test', function (req, res, next){
db.query("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where 
TABLE_NAME = 'registros';", function (error, results, fields) {

if (error) throw error;
res.render('test', {
columnNames: results
});});
db.query("SELECT * FROM registros", function (error, resp, fields) {

if (error) throw error;
res.render('test', {
dataRegistros: resp
});});

});

I understand that it may be because it is rendering twice in the same route. What would be the correct method to make several SQL queries and return them to a file in view?

Regards!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
202 views
Welcome To Ask or Share your Answers For Others

1 Answer

According to mysql nodejs driver you can setup it o combine the queries and return an array with results

You must set this when you create the connection:

mysql.createConnection({multipleStatements: true});

Then make the request with both queries

router.post('/test', function (req, res, next) {

  var queries = [
    "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'registros'",
    "SELECT * FROM registros"
  ];

  db.query(queries.join(';'), function (error, results, fields) {

    if (error) throw error;

    res.render('test', {
      columnNames: results[0], // First query from array
      dataRegistros: resp      // Second query from array
    });

  });

});

But let me ask a question, why would you need to query column names when actually you query all rows and can get columns from there?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...