将MySQL数据显示为HTML div - Node.js

时间:2018-05-06 15:36:44

标签: mysql node.js

我正在努力将MySQL中的数据输出到我的HTML页面中。我需要有关如何从MySQL提取数据并将其显示在我的HTML页面上的建议。如下所示,服务器代码连接到HTML页面和MySQL,但我只需要将MySQL数据输入HTML div。

的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 + '/'));

var connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mywebsite"
});

connection.connect();

app.get('/', function(req, res) {
    connection.query("SELECT * FROM chat", function(err, result) {
        if(err) throw err;
        console.log(result);
        res.send(JSON.stringify(result[0].Message));
    });
    res.sendFile(__dirname + '/index.html');
});

app.listen(3000, function () {
    console.log('Connected to port 3000');
});

1 个答案:

答案 0 :(得分:1)

取决于您的需求:

·服务器呈现数据:

您需要view engine,例如hbs

as Robert Moskal stated in a comment to your question, it is very clearly explained

·客户端呈现数据:

您需要:

1] app.get("/")中提取数据库查询并将其作为其中的一部分     app.post("/")

中的逻辑
app.get("/",(req, res)=>{res.sendFile(__dirname+"/index.html")})

app.post('/',(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) }
 })
})   

2] 从您的客户端向新路由器的帖子路径发出POST请求。

3] 在客户端接收响应并操纵DOM以显示数据。

Here you can find an example of sending a post request and receiving the response