Render multiple queries in Node Express

0

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 not set headers after they are sent.

And the 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?

Greetings!

    
asked by Kryphon 09.09.2018 в 08:27
source

2 answers

0
  

According to the mysql nodejs driver, you can configure it or combine?> queries and return an array with results

     

You must configure this when you create the connection:

mysql.createConnection({multipleStatements: true});
  

Next, make the request with both questions

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

});

});

This works.

    
answered by 09.09.2018 / 19:48
source
0

You can nest your callbacks (If they are only 2 it is still legible).

router.post('/test', function (req, res, next) {
    db.query("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'registros'; ", (error, results, fields) => {
        if (error) throw error;
        db.query("SELECT * FROM registros", (error, resp, fields) => {
            if (error) throw error;
            res.render('test', {
                dataRegistros: resp,
                columnNames: results
            });
        });
    });
});
    
answered by 10.09.2018 в 18:16