2017-08-01 105 views
0

我在连接mysql时遇到了一些错误,我无法弄清楚。 下面的基本连接代码运行良好。Node + 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 
    }); 
}); 

请让我知道,如果我错过了任何影响中间。谢谢。

+0

揣摩那个犯错变量包含 –

+0

它所引发任何错误: -/ – Gayathri

+0

是不会,但有一点是检查它包含的内容,使用'console.log(err)'为了更好的理解。 –

回答

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

+0

大拇指朝下。行为仍然是一样的。 – Gayathri

+0

有趣的部分是,我甚至执行插入查询具有相同的结构,我用于选择和运作良好。不知道为什么不选择。 – Gayathri