在下面的代碼中,我試圖從MySQL中檢索數據並將它們顯示在HTML頁面中。我測試通過顯示在控制檯中的數據連接,它工作得很好,但問題是,數據不能顯示在HTML頁面上:顯示從節點js中的MySQL數據庫中檢索到的數據
var http = require("http");
var mysql = require('mysql');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
//response.end('Hello World\n');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'somepass',
database : 'Students',
}
);
connection.connect();
var queryString = 'SELECT * FROM Student';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
response.end('Name: ', rows[i].Name); //this doesn't work, it only shows Name: but doesn't show the retrieved name from the databased
console.log('Name: ', rows[i].Name); //this works fine
}
});
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
任何人可以幫助我解決這個問題?
據我所知response.end用於發送流中的最後一位。你應該首先使用response.write在流中寫入,然後才結束(你正在做一個循環) –