【发布时间】:2018-10-12 13:24:34
【问题描述】:
这是我第一次学习 Node.js。我正在尝试将 MySQL 中的数据打印到我的 HTML 页面中,但是每当我在浏览器 http://localhost:3000/index.html 上加载我的网站时,我都会在网页上收到以下消息:Cannot GET /index.html。但是,当我在浏览器上加载这个 http://localhost:3000/rows/ 时,我从 MySQL 中获取数据作为输出 [{"ID":1,"Name":"Wendy Smith","Message":"Hello, how are you?"}]。
我已经发布了下面的代码。我正在努力解决这个问题。
index.html
<html>
<head>
<title>My db rows</title>
</head>
<body>
<h1>My Data</h1>
<div id="output"></div>
<script type="text/javascript">
var opts = {
url: 'http://localhost:3000/rows/'
};
fetch(opts)
.then((res) => {
if (res.ok) {
return res.json();
}
})
.catch(console.log);
</script>
</body>
</html>
server.js
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: "mywebsite"
});
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('Connected to port 3000!');
});
【问题讨论】:
标签: javascript html mysql node.js