gpt4 book ai didi

javascript - 使用 Node.js 将 MySQL 数据打印到 HTML 页面

转载 作者:太空宇宙 更新时间:2023-11-03 11:30:43 25 4
gpt4 key购买 nike

这是我第一次学习 Node.js。我试图将 MySQL 中的数据打印到我的 HTML 页面中,但是每当我在浏览器 http://localhost:3000/index.html 上加载我的网站时,我都会在网页上收到此消息: 无法获取/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!');
});

最佳答案

您缺少通过 index.html 页面路由请求的中间件代码。例如,您在 app.js 中设置了一个 const 变量:

const indexRouter = require("./app_server/router/index.html");

您可以这样呈现 html 页面:

app.use("/", indexRouter);

如果您想使用 express.static 中间件来提供 public 文件夹中的静态文件,只需使用:

app.use(express.static(__dirname + "/public"));

关于javascript - 使用 Node.js 将 MySQL 数据打印到 HTML 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50134562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com