我在 express 中连接 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