You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Node.js数据库查询数据传递至__dirname目录下的HTML文件

如何将数据库数据渲染到HTML页面?

你当前的问题是:已经成功从数据库获取到rows数据,但用res.sendFile发送静态HTML时,页面里的{{rows}}无法显示数据。这是因为res.sendFile仅负责发送静态文件,不会解析模板语法,也不会把数据传递到页面中。

下面提供两种可行的解决方案:

方案一:使用模板引擎(以EJS为例)

模板引擎可以在服务端把数据注入到HTML模板中,生成最终的HTML页面返回给浏览器。

  1. 安装EJS
    在项目根目录执行命令:

    npm install ejs
    
  2. 配置Express使用EJS
    在你的主入口文件(比如app.js)中添加以下配置:

    const express = require('express');
    const app = express();
    
    // 设置模板引擎为EJS
    app.set('view engine', 'ejs');
    // 可选:如果你的模板不在默认的views文件夹,可设置路径
    // app.set('views', path.join(__dirname, 'your-template-folder'));
    
  3. 修改路由代码
    把res.sendFile替换为res.render,并传递数据库查询到的rows数据:

    router.get('/', function(req, res) {
        connection.connect((err) => {
            if (err) throw err;
            console.log('this is the home route');
    
            connection.query('SELECT * FROM products', (err, rows) => {
                if (err) throw err;
                console.log('Data received from Db:');
                console.log(rows);
                // 渲染index.ejs模板,将rows数据以products为名传递
                res.render('index', { products: rows });
            });
        });
    });
    
  4. 修改模板文件
    将原来的index.html重命名为index.ejs,放到项目根目录的views文件夹下(如果没有则新建),然后用EJS语法遍历数据:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>产品列表</h1>
        <ul>
            <% products.forEach(product => { %>
                <li>
                    条码:<%= product.barcode %> | 描述:<%= product.product_description %> | 数量:<%= product.quantity %>
                </li>
            <% }) %>
        </ul>
    </body>
    </html>
    

方案二:前端AJAX请求数据(前后端分离模式)

如果不想用模板引擎,可以让前端通过AJAX请求后端接口获取数据,再用JavaScript动态渲染页面。

  1. 修改路由,新增API接口
    拆分路由,一个返回静态HTML,一个返回JSON格式的数据库数据:

    // 返回静态HTML页面
    router.get('/', function(req, res) {
        res.sendFile(path.join(__dirname + '/index.html'));
    });
    
    // 提供产品数据的API接口
    router.get('/api/products', function(req, res) {
        connection.connect((err) => {
            if (err) throw err;
            connection.query('SELECT * FROM products', (err, rows) => {
                if (err) throw err;
                // 返回JSON格式的数据
                res.json(rows);
            });
        });
    });
    
  2. 修改HTML页面,添加动态渲染逻辑
    在HTML中添加JavaScript代码,发起请求获取数据并渲染:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>产品列表</h1>
        <div id="productContainer"></div>
    
        <script>
            // 发起fetch请求获取产品数据
            fetch('/api/products')
                .then(response => response.json())
                .then(products => {
                    const container = document.getElementById('productContainer');
                    // 生成产品列表的HTML
                    let listHtml = '<ul>';
                    products.forEach(product => {
                        listHtml += `
                            <li>
                                条码:${product.barcode} | 描述:${product.product_description} | 数量:${product.quantity}
                            </li>
                        `;
                    });
                    listHtml += '</ul>';
                    // 将生成的HTML插入到页面中
                    container.innerHTML = listHtml;
                })
                .catch(error => console.error('加载数据失败:', error));
        </script>
    </body>
    </html>
    

内容的提问来源于stack exchange,提问作者denis kiplangat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 09:55:38