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

如何将Node.js获取的MySQL数据传递至index.html并展示?

解决Node.js中MySQL数据在index.html展示的问题

你当前的代码是直接返回拼接好的HTML片段,没有结合独立的index.html页面。要实现将数据库数据嵌入index.html,以下是两种最常用的方案:

方案一:使用模板引擎(服务器端渲染)

以EJS为例,它可以让你在HTML文件中嵌入动态数据,由Node.js在服务器端渲染完成后返回给浏览器。

步骤1:安装EJS

npm install ejs

步骤2:修改Node.js代码

配置视图引擎并传递数据库查询结果到模板:

const express = require("express");
const mysql = require('mysql2');
const app = express();

// 配置EJS为视图引擎
app.set('view engine', 'ejs');
// 指定视图文件存放目录(默认是项目根目录下的views文件夹)
app.set('views', './views');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'somePassword',
  database: 'someDatabase'
});

app.get('/', (req, res) => {
  connection.query('SELECT * FROM someTable', (error, results) => {
    if (error) {
      console.error(error);
      return res.status(500).send('An error occurred');
    }
    // 渲染index.ejs模板,将查询结果以products变量传递过去
    res.render('index', { products: results });
  });
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

步骤3:创建视图文件

在项目根目录下新建views文件夹,创建index.ejs(把你原有的index.html内容迁移过来,在需要展示数据的位置嵌入EJS语法):

<!DOCTYPE html>
<html>
<head>
  <title>产品列表</title>
  <style>
    .search_product {
      margin: 10px;
      padding: 15px;
      border: 1px solid #ddd;
    }
    .product_title { margin-top: 0; }
  </style>
</head>
<body>
  <h1>产品列表</h1>
  <!-- 遍历products数组,渲染每个产品信息 -->
  <% products.forEach(product => { %>
    <div class="search_product">
      <h5 class="product_title"><%= product.name %></h5>
      <p class="product_description">价格: <%= product.price %></p>
      <p class="product_price">品牌: <%= product.brand %></p>
    </div>
  <% }) %>
</body>
</html>

方案二:前端AJAX请求数据(客户端渲染)

这种方式适合前后端分离场景,Node.js只提供数据接口,前端页面自行请求数据并动态渲染。

步骤1:修改Node.js代码

托管静态文件并提供数据接口:

const express = require("express");
const mysql = require('mysql2');
const app = express();

// 托管public目录下的静态文件(index.html放在这里)
app.use(express.static('public'));

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'somePassword',
  database: 'someDatabase'
});

// 提供产品数据的API接口
app.get('/api/products', (req, res) => {
  connection.query('SELECT * FROM someTable', (error, results) => {
    if (error) {
      console.error(error);
      return res.status(500).json({ error: 'An error occurred' });
    }
    res.json(results);
  });
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

步骤2:创建前端页面

在项目根目录下新建public文件夹,创建index.html,用JavaScript发起请求并渲染数据:

<!DOCTYPE html>
<html>
<head>
  <title>产品列表</title>
  <style>
    .search_product {
      margin: 10px;
      padding: 15px;
      border: 1px solid #ddd;
    }
    .product_title { margin-top: 0; }
  </style>
</head>
<body>
  <h1>产品列表</h1>
  <div id="products-container"></div>

  <script>
    // 发起AJAX请求获取数据
    fetch('/api/products')
      .then(res => res.json())
      .then(products => {
        const container = document.getElementById('products-container');
        products.forEach(product => {
          const productDiv = document.createElement('div');
          productDiv.className = 'search_product';
          productDiv.innerHTML = `
            <h5 class="product_title">${product.name}</h5>
            <p class="product_description">价格: ${product.price}</p>
            <p class="product_price">品牌: ${product.brand}</p>
          `;
          container.appendChild(productDiv);
        });
      })
      .catch(err => {
        console.error('数据加载失败:', err);
        document.getElementById('products-container').innerHTML = '<p>加载数据失败,请稍后重试</p>';
      });
  </script>
</body>
</html>

两种方案的区别

  • 模板引擎是服务器端渲染:页面加载时已经包含完整的渲染后HTML,对SEO更友好。
  • AJAX是客户端渲染:页面先加载静态内容,再异步请求数据渲染,适合需要动态更新数据的交互场景。

内容的提问来源于stack exchange,提问作者Web Rise

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:22:50