0

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

1 Answer 1

2

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"));
Sign up to request clarification or add additional context in comments.

10 Comments

On the sever response, I get Error: Cannot find module
Can you test this out without defining the const variable as such: app.use("/", function(req, res) { res.send("This is a test");}
What do you mean ? Did you sort it out ?
This is a test is displayed on my webpage
Which then means you have a solution :) You just have to wire your html page to the code, wherever it resides in your local directory
|

Your Answer

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