Node + Mysql - 连接问题

时间:2017-08-01 18:47:58

标签: javascript mysql node.js mean-stack

我在Express中连接mysql时遇到了一些错误,我无法弄清楚。 下面的基本连接代码运行良好。

 var connection = mysql.createConnection({
      host     : 'localhost',
      user:'root',
      password:'',
      database :'testdb'
    });
    connection.connect();
    connection.query('SELECT * from test2table', function (err, data) {
      if (err) throw err

     console.log('The solution is: '+JSON.stringify(data)); -->could obtain data
    });

但是当在get / post方法中使用时,我不会得到回应。像下面的代码:

var connection = mysql.createConnection({
  host : 'localhost',
  user:'root',
  password:'',
  database :'testdb'
});
connection.connect(function(err){
        if(err) throw err;
        console.log("connected");
    });



 app.get('/api/records',function(req,res){
        connection.query('SELECT * from test2table', function (err, data) {
            console.log(data);--> get blank response
    });
 });

如果我错过任何影响的事情,请告诉我。三江源。

1 个答案:

答案 0 :(得分:0)

你可以试试app.locals吗?

var connection = mysql.createConnection({
  host : 'localhost',
  user:'root',
  password:'',
  database :'testdb'
});
connection.connect(function(err){
        if(err) throw err;
        console.log("connected");
});

app.locals.connection = connection;
app.get('/api/records',function(req,res){
        app.locals.connection.query('SELECT * from test2table', function (err, data) {
            console.log(data);--> get blank response
    });
 });

在此处查看更多详情:http://expressjs.com/en/api.html#app.locals