本文介绍了节点+ Mysql-连接问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在连接MySQL中犯了一些错误,但我无法弄清楚.下面的基本连接代码效果很好.

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

但是当涉及到在get/post方法中使用时,我没有得到响应.像下面的代码:

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.

推荐答案

您可以尝试使用app.locals吗?

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

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

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

这篇关于节点+ Mysql-连接问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 15:44
查看更多