2017-08-01 102 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