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

Angular 4从MySQL数据库展示表格数据(含日期)技术求助

在Node.js Express中展示MySQL带日期数据的表格完整方案

别担心,我给你整理了一个一步步实现的完整示例,连你可能遇到的坑都提前说明白了,跟着做就能搞定:

1. 准备工作:安装依赖

首先初始化你的Express项目,然后安装需要的包:

npm init -y
npm install express mysql2 ejs
  • express:核心Web框架
  • mysql2:比原生mysql包性能更好,支持Promise语法,更适合异步场景
  • ejs:贴近HTML的模板引擎,新手友好,用来快速渲染表格

2. 数据库准备与连接配置

先确保你的MySQL里有测试表,比如我用一个user表做示例:

CREATE TABLE user (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  register_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- 插入几条测试数据
INSERT INTO user (username) VALUES ('Alice'), ('Bob'), ('Charlie');

然后在项目根目录创建db.js,用来管理数据库连接池(比单个连接更稳定):

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: 'localhost', // 你的MySQL服务地址
  user: 'root', // 你的MySQL用户名
  password: 'your_password', // 你的MySQL密码
  database: 'your_database', // 你的目标数据库名
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

module.exports = pool;

3. 后端路由:查询数据并传递到前端

修改app.js,配置模板引擎,编写查询路由:

const express = require('express');
const app = express();
const pool = require('./db');

// 设置模板引擎为EJS
app.set('view engine', 'ejs');
// 明确指定模板文件目录(默认就是views,写上更清晰)
app.set('views', './views');

// 首页路由:查询数据并渲染表格
app.get('/', async (req, res) => {
  try {
    // 重点:用DATE_FORMAT在SQL里直接格式化日期,避免前端时区偏移问题
    const [rows] = await pool.execute(
      'SELECT id, username, DATE_FORMAT(register_date, "%Y-%m-%d %H:%i:%s") AS formatted_date FROM user'
    );
    // 把查询到的数据传给EJS模板
    res.render('index', { users: rows });
  } catch (err) {
    console.error('查询数据失败:', err);
    res.status(500).send('服务器出错了');
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

4. 前端模板:渲染带日期的表格

在项目根目录创建views文件夹,然后创建index.ejs:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>用户数据表格</title>
  <style>
    table { border-collapse: collapse; width: 80%; margin: 20px auto; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
    th { background-color: #f2f2f2; }
  </style>
</head>
<body>
  <h1 style="text-align: center;">用户注册数据</h1>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>用户名</th>
        <th>注册日期</th>
      </tr>
    </thead>
    <tbody>
      <% users.forEach(user => { %>
        <tr>
          <td><%= user.id %></td>
          <td><%= user.username %></td>
          <td><%= user.formatted_date %></td>
        </tr>
      <% }) %>
    </tbody>
  </table>
</body>
</html>

5. 常见错误排查

如果你之前遇到报错,大概率是这几个原因:

  • 数据库连接失败:检查db.js里的host、user、password、database是否正确,确保MySQL服务正在运行(可以用mysql -u root -p命令测试连接)
  • 日期显示异常:如果没在SQL里格式化,前端可以用new Date(user.register_date).toLocaleString()处理,但还是推荐SQL里格式化更可靠,避免时区偏差
  • 模板引擎报错:确保views目录存在,index.ejs在该目录下,并且app.js里正确设置了模板引擎
  • 路由404:确保访问的是http://localhost:3000,而不是其他路径

运行测试

执行node app.js,然后打开浏览器访问http://localhost:3000,就能看到带格式化日期的用户数据表格了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:44:27