繁体   English   中英

节点+ Mysql-连接问题

[英]Node + Mysql - Issue with connection

我在连接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
    });
 });

请让我知道我是否错过任何会影响的事情。 谢谢。

您可以尝试使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM