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

如何将基于HTTP模块的Node.js MySQL数据展示代码改为Express实现?

把原生HTTP模块的MySQL数据展示代码转成Express版本

没问题!我来帮你把基于Node.js原生HTTP模块的MySQL数据展示代码转换成Express版本,毕竟Express封装了很多原生HTTP的细节,用起来更简洁顺手,刚好你也熟悉它~

第一步:先安装依赖

首先确保你已经安装了Express和MySQL驱动(这里用mysql2,比旧的mysql包更稳定),在项目目录下运行:

npm install express mysql2

第二步:Express版本的完整代码

下面是对应功能的Express实现,你只需要替换成自己的数据库配置和表名就行:

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

// 创建Express应用实例
const app = express();
// 设置服务器端口
const port = 3000;

// 配置MySQL数据库连接信息(替换成你自己的)
const db = mysql.createConnection({
  host: 'localhost',
  user: '你的数据库用户名',
  password: '你的数据库密码',
  database: '你的数据库名'
});

// 连接数据库
db.connect((err) => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  console.log('✅ 成功连接到MySQL数据库');
});

// 定义根路由:访问主页时返回包含MySQL数据的HTML
app.get('/', (req, res) => {
  // 替换成你要查询的表名
  const querySQL = 'SELECT * FROM 你的表名';

  // 执行数据库查询
  db.query(querySQL, (err, results) => {
    if (err) {
      console.error('查询数据出错:', err);
      // 返回500错误给前端
      return res.status(500).send('获取数据失败,请稍后重试');
    }

    // 如果查询结果为空,返回提示
    if (results.length === 0) {
      return res.send('<h1 style="text-align:center;">数据库中暂无数据</h1>');
    }

    // 动态生成HTML页面,把查询结果渲染进去
    const htmlContent = `
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <title>MySQL数据展示</title>
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { font-family: Arial, sans-serif; padding: 20px; }
          h1 { text-align: center; margin-bottom: 30px; color: #333; }
          table { border-collapse: collapse; width: 90%; margin: 0 auto; }
          th { background-color: #f5f5f5; padding: 12px; text-align: left; border-bottom: 2px solid #ddd; }
          td { padding: 10px; border-bottom: 1px solid #eee; }
          tr:hover { background-color: #f9f9f9; }
        </style>
      </head>
      <body>
        <h1>数据库数据展示</h1>
        <table>
          <!-- 动态生成表头 -->
          <thead>
            <tr>
              ${Object.keys(results[0]).map(column => `<th>${column}</th>`).join('')}
            </tr>
          </thead>
          <!-- 动态生成数据行 -->
          <tbody>
            ${results.map(row => `
              <tr>
                ${Object.values(row).map(value => `<td>${value}</td>`).join('')}
              </tr>
            `).join('')}
          </tbody>
        </table>
      </body>
      </html>
    `;

    // 把生成的HTML发送给前端
    res.send(htmlContent);
  });
});

// 启动Express服务器
app.listen(port, () => {
  console.log(`🚀 服务器已启动,访问地址:http://localhost:${port}`);
});

和原生HTTP版本的核心区别

  1. 路由处理更简洁:用app.get('/')直接定义主页的请求处理,不用像原生HTTP那样手动判断req.url和请求方法
  2. 响应处理更方便:Express的res.send()会自动帮你设置响应头、处理响应结束,不用手动写res.write()和res.end()
  3. 错误处理更直观:可以用res.status(500)直接返回错误状态码,前端能更清晰地感知问题

额外优化建议

如果你的页面比较复杂,推荐用模板引擎(比如EJS)来分离HTML和逻辑,这样代码更易维护:

  1. 安装EJS:npm install ejs
  2. 设置模板引擎:app.set('view engine', 'ejs')
  3. 在项目根目录创建views文件夹,新建index.ejs文件写HTML结构,然后在路由里用res.render('index', { data: results })把数据传给模板渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:55:25