如何使用Node.js将MySQL查询数据传递到index.html静态页面
实现方案说明
前置注意点
- 你当前代码中Express监听的是
3001端口,若你实际访问localhost:3000/users可正常返回数据,建议检查端口配置是否一致,避免后续调用出错。
方案1:前端Fetch调用接口(适合前后端分离场景)
该方案不需要修改现有/users接口逻辑,只需要新增跨域支持,然后在HTML中发起请求渲染数据即可。
操作步骤
- 安装跨域中间件解决跨域限制
npm install cors
- 在Express代码中引入并启用cors
const cors = require('cors'); // 放在其他app.use中间件上方 app.use(cors());
- 编写
index.html代码,通过原生Fetch请求接口渲染数据
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>用户列表</title> </head> <body> <h1>用户列表</h1> <ul id="userList"></ul> <script> // 替换成你实际的接口地址 fetch('http://localhost:3000/users') .then(res => res.json()) .then(users => { const list = document.getElementById('userList'); users.forEach(user => { const li = document.createElement('li'); // 假设user对象有name、email字段,可根据实际字段修改 li.textContent = `用户名:${user.name},邮箱:${user.email}`; list.appendChild(li); }) }) .catch(err => console.error('请求失败:', err)); </script> </body> </html>
方案2:服务端模板渲染(适合同域部署,无需前端单独发请求)
该方案直接由Express服务端把数据嵌入HTML后返回,不需要跨域配置。
操作步骤
- 安装EJS模板引擎
npm install ejs
- 在Express代码中配置模板引擎
// 放在路由配置上方 app.set('view engine', 'ejs'); // 新建views文件夹,把模板文件放在该目录下 app.set('views', './views');
- 在
views目录下新建index.ejs模板文件
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>用户列表</title> </head> <body> <h1>用户列表</h1> <ul> <% users.forEach(user => { %> <li>用户名:<%= user.name %>,邮箱:<%= user.email %></li> <% }) %> </ul> </body> </html>
- 新增页面路由,渲染时传入用户数据
app.get('/index.html', (req, res) => { mysqlConnection.query('SELECT * FROM users',(err, rows) => { if (err) { return res.status(500).send('查询数据失败'); } res.render('index', { users: rows }); }) })
配置完成后直接访问http://localhost:3000/index.html即可看到带数据的页面。
额外优化建议
- 生产环境不要直接
throw err,应返回规范的错误响应,避免服务直接崩溃 - 数据库账号密码、端口等敏感信息不要硬编码,建议通过
.env环境变量配置
内容的提问来源于stack exchange,提问作者Evgeny P
相关产品推荐
相关产品推荐

