我正在尝试从MySQL提取数据并将其显示在HTML页面上,但是当我在浏览器上运行以下代码时http://localhost:3000
,数据不会显示在页面上。如果有人可以帮助我解决这个问题,我将不胜感激。
index.html
<!DOCTYPE>
<html>
<head>
<title>Data from MySQL</title>
</head>
<body>
<div id="output_message"></div>
</body>
</html>
app.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', express.static(__dirname + '/'));
app.set('view engine', 'html');
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
connection.connect();
app.get('/',(req, res) => {
connection.query("SELECT * FROM chat",(err, result) => {
if(err) {
console.log(err);
res.json({"error":true});
}
else {
console.log(result);
res.json(result);
}
});
});
app.listen(3000, function () {
console.log('Connected to port 3000');
});
您需要考虑多个因素:
1-当您要使用通过HTML文件发送的POST方法时,必须具有
<form action="Name of your processing file" method="POST">YOUR FORM HERE</form>
然而; 如果您只是尝试调用数据库并获取数据,则只需执行
您在GET方法中的逻辑如下:
app.get('/',(req, res) => {
connection.connect(function(err) {
if(err) throw err;
else {
connection.query("SELECT * FROM chat",(err, result) => {
if(err) {
console.log(err);
res.json({"error":true});
}
else {
console.log(result);
res.json(result);
}
});
}
});
});
***您可能会问index.html呢。有两个响应:
1-res.sendFile(__dirname + "/YOURPAGE-Name.html");
在您要发送文件时使用
结果是
例:
app.get("/",(req, res) => {
res.sendFile(__dirname + "/Welcome.html");
});
Welcome.html
<!DOCTYPE>
<html>
<head>
<title>Data from MySQL</title>
</head>
<body>
<p>Welcome to my page</p>
</body>
</html>
2-res.sendFile(__dirname + "/index.html");
当您想要获得
初始页面,这样您就可以在要处理的应用程序中拥有表单
例:
app.get("/",(req, res) => {
res.sendFile(__dirname + "/index.html");
});
index.html
<!DOCTYPE>
<html>
<head>
<title>Data from MySQL</title>
</head>
<body>
<form action="/" method="post">
//YOUR FORM HERE
</form>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句