Node + Mysql - Issue with connection

2019-09-16 17:57发布

问题:

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