1

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!

0

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Hi. The reason I did that was ... just to experiment! I asked myself what happens if I need to make several queries from a single route and send them. I wanted to populate an html table by first getting the names of the columns and then the entire record for the body of the table. Thanks, I'll try what you suggested!
0

To make several queries from a single route use async npm library

npm install --save async

then use parallel method and functions to make the several queries for database with the callback.

async.parallel({
   one: function(callback) {
      callback(null, 'abc\n');
   },
   two: function(callback) {
     callback(null, 'xyz\n');
   }
}, function(err, results) {
    if (error) throw error;
      res.render('test', {
        columnNames: results.one, 
        dataRegistros: results.two      
     });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.