【问题标题】:Print MySQL data into HTML page using Node.js使用 Node.js 将 MySQL 数据打印到 HTML 页面中
【发布时间】:2018-10-12 13:24:34
【问题描述】:

这是我第一次学习 Node.js。我正在尝试将 MySQL 中的数据打印到我的 HTML 页面中,但是每当我在浏览器 http://localhost:3000/index.html 上加载我的网站时,我都会在网页上收到以下消息:Cannot GET /index.html。但是,当我在浏览器上加载这个 http://localhost:3000/rows/ 时,我从 MySQL 中获取数据作为输出 [{"ID":1,"Name":"Wendy Smith","Message":"Hello, how are you?"}]

我已经发布了下面的代码。我正在努力解决这个问题。

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

【问题讨论】:

    标签: javascript html mysql node.js


    【解决方案1】:

    您缺少通过 index.html 页面路由请求的中间件代码。例如,您在 app.js 中设置了一个 const 变量,如下所示:

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

    您可以像这样渲染html 页面:

    app.use("/", indexRouter);
    

    如果您想使用 express.static 中间件来提供位于 public 文件夹中的静态文件,只需使用:

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

    【讨论】:

    • 在服务器响应中,我收到Error: Cannot find module
    • 你能在不定义 const 变量的情况下测试一下吗:app.use("/", function(req, res) { res.send("This is a test");}
    • 什么意思?你解决了吗?
    • This is a test 显示在我的网页上
    • 这意味着您有一个解决方案 :) 您只需将您的 html 页面连接到代码,无论它位于您的本地目录中的任何位置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多