Pergunta

When I run my server.js which is like

...
var app = require('express')(), mysql = require('mysql');
var mysqlConn = mysql.createConnection(connParam);
var controllers = {mysql: require('./controller/mysql.js')(app, mysqlConn, null)};
...

and the controller/mysql.js

...
module.exports = function (app, conn, data) {
...
app.get('/mysql', mysqlController);
function mysqlController (req, res, next) {
  console.log('reached mysqlController');
  conn.connect(function (err) {
    if (!err) {
      console.log('mysql connection established');
    }
    else {
      console.log('mysql connection ERROR');
    }
  });
  conn.query('select * from users', function (err, sqlRes) {
    if (!err) {
      console.log('\tdb query success from conn');
      app.render('mysql/index.jade', {title: 'App | MySql:index', result: sqlRes},
      function (err, html) {
        console.log('\trendering mysql/index');
        res.send(html);
        conn.end(function (err) {
          console.log('mysql connection closed');
        });
      });
    }
    else {
      console.log('\tError processing query from db');
      res.send("ERROR 505");
    }
  });
}

For the 1st request I get the results as expected but the second time, it's not connecting...

:~/workspace/noder$ node server.js
Server listening to port: 8080
reached mysqlController
mysql connection established
    db query success from conn
    rendering mysql/index
mysql connection closed
reached mysqlController
mysql connection ERROR
    Error processing query from db

Can someone please help me out here...

Foi útil?

Solução

It's because you're calling connect() on an already connected connection.. Try calling connect() in the controller/mysql function itself and not in the app.get(). This way connect() will only be called once..

Also if it doesn't fix it, in your console log of the error, print the error as well console.log('mysql error', err);

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top