简体   繁体   中英

Print MySQL data into HTML page using Node.js

This is my first time learning Node.js. I am trying to print the data in MySQL into my HTML page, but whenever I load my website on the browser http://localhost:3000/index.html , I get this message on the webpage: Cannot GET /index.html . However when I load this http://localhost:3000/rows/ on the browser, I get the data from MySQL as the output [{"ID":1,"Name":"Wendy Smith","Message":"Hello, how are you?"}] .

I have posted the code below. I am struggling to resolve this issue.

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!');
});

You are missing the middleware code to route the request through the index.html page. Say for example you have set a const variable in your app.js as such:

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

You can render the html page as such:

app.use("/", indexRouter);

In case you want to use the express.static middleware to serve static files that are in a public folder, just use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM