如何用Node服务器在HTML页面展示PostgreSQL日期并渲染接口数据至表格
问题1:Node服务器从PostgreSQL取日期并在HTML页面展示
- 安装依赖:执行
npm install pg express安装PostgreSQL驱动和Express框架 - Node端实现数据库查询与接口返回:
const { Pool } = require('pg'); const express = require('express'); const app = express(); // 配置PostgreSQL连接 const pool = new Pool({ user: '你的数据库用户名', host: 'localhost', database: '你的数据库名', password: '你的数据库密码', port: 5432, }); // 提供带日期数据的接口 app.get('/date-data', async (req, res) => { try { // 查询包含日期字段的数据(这里以created_at为例) const result = await pool.query('SELECT id, title, created_at FROM your_table'); // 格式化日期:把PostgreSQL返回的Date对象转成易读格式 const formattedData = result.rows.map(item => ({ ...item, // 自定义日期格式为YYYY-MM-DD HH:mm:ss created_at: `${item.created_at.getFullYear()}-${(item.created_at.getMonth()+1).toString().padStart(2, '0')}-${item.created_at.getDate().toString().padStart(2, '0')} ${item.created_at.getHours().toString().padStart(2, '0')}:${item.created_at.getMinutes().toString().padStart(2, '0')}:${item.created_at.getSeconds().toString().padStart(2, '0')}` })); res.json(formattedData); } catch (err) { console.error(err); res.status(500).send('数据查询失败'); } }); app.listen(3000, () => console.log('服务器运行在3000端口')); - 前端展示:通过fetch请求
/date-data接口,将返回的日期字段插入到HTML对应位置即可,逻辑与问题2的表格渲染一致。
问题2:前端Fetch渲染JSON数据到HTML表格
首先确保HTML表格结构正确,包含表头和用于填充数据的tbody:
<table border="1"> <thead> <tr> <th>Código</th> <th>Nome</th> </tr> </thead> <tbody id="clientes"></tbody> </table>
然后优化你的Fetch代码,补充响应校验并避免重复渲染:
fetch('/clientes') .then(response => { // 校验响应是否成功,避免解析错误的响应 if (!response.ok) { throw new Error(`请求错误:${response.status}`); } return response.json(); }) .then(data => { const clientesTable = document.getElementById('clientes'); // 先清空表格,防止重复加载数据 clientesTable.innerHTML = ''; // 循环生成表格行 data.forEach(cliente => { const row = document.createElement('tr'); const codigoCell = document.createElement('td'); const nomeCell = document.createElement('td'); codigoCell.textContent = cliente.codigo; nomeCell.textContent = cliente.nome; row.appendChild(codigoCell); row.appendChild(nomeCell); clientesTable.appendChild(row); }); }) .catch(error => console.error('加载数据出错:', error));
如果字段较多,也可以用模板字符串简化代码:
// 替换forEach内的DOM创建逻辑 const rowHtml = ` <tr> <td>${cliente.codigo}</td> <td>${cliente.nome}</td> </tr> `; clientesTable.innerHTML += rowHtml;
内容的提问来源于stack exchange,提问作者linuser1990
相关产品推荐
相关产品推荐

