0

当我运行我的 server.js 时,就像

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

和控制器/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");
    }
  });
}

对于第一个请求,我得到了预期的结果,但第二次,它没有连接......

:~/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

有人可以在这里帮助我吗...

4

1 回答 1

1

这是因为您正在调用connect()已连接的连接。尝试connect()在控制器/mysql 函数本身中调用,而不是在app.get(). 这种方式connect()只会被调用一次..

此外,如果它没有修复它,在您的错误控制台日志中,也打印错误console.log('mysql error', err);

于 2013-09-17T03:18:17.767 回答