您需要查看creating an http server才能將這些結果發送到html網站。
var express = require('express');
var app = express();
app.use(express.static('public'))
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'db'
});
app.get('/rows', function (req, res) {
connection.connect();
connection.query('SELECT * FROM users', function(err, rows, fields)
{
connection.end();
if (err) throw err;
res.json(rows);
});
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
運行此文件將在您的機器上的端口3000上創建一個服務器。
在您的項目中,在根級別創建一個名爲public
的目錄。在那裏,你可以創建一個名爲index.html
的東西,如以下文件:
<html>
<head>
<title>My db rows</title>
</head>
<body>
<div id="table"></div>
<script type="text/javascript">
var opts = {
url: 'http://localhost:3000/rows/'
};
fetch(opts)
.then((res) => {
if (res.ok) {
return res.json();
}
})
.then((rows) => {
for (let row of rows) {
// row will be a mysql row -- you can loop over these and do what you want with them
}
})
.catch(console.log);
</script>
</body>
</html>
注:我使用的是新的API獲取要執行我的要求,但是你可以很容易地使用jquery或XHR。獲取API可以更詳細地解釋here。
然後在瀏覽器中導航到http://localhost:3000/index.html
以查看結果。