Node + Mysql - Issue with connection

久未见 提交于 2019-12-25 09:31:28

问题


I do some mistake with connecting mysql in express which i couldn't figure out. The basic connection code below works well.

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

But when it comes to use inside a get/post method , i donot get a response. Like code below:

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

Please let me know if i missed anything inbetween which affects. Thankyou.


回答1:


Can you try with 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
    });
 });

See more details here: http://expressjs.com/en/api.html#app.locals



来源:https://stackoverflow.com/questions/45445542/node-mysql-issue-with-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!