0

I am struggling to output the data from MySQL into my HTML page. I need suggestions on how I can extract data from MySQL and display it on my HTML page. As you can see below, the server code connects to the HTML page and MySQL, but I just need to input the MySQL data into the 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

1 Answer 1

0

Dependind on your needs :

· Server Renders Data :

You will be needing a view engine such as hbs

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


· Client Renders Data :

You will need to :

1] extract the db query from the app.get("/") and make it part of the logic in 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] make a POST request from your client to the new router's post path.

3] receive the response at the client and manipulate the DOM to display the data.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.