如何通过Localhost在HTML中展示MS SQL查询的name、id数据?
解决方案
1. 核心问题说明
你直接在HTML里引入的index.js是Node.js环境的代码,浏览器不支持require、mssql这类Node专属模块/API,必须通过后端接口+前端请求渲染的方式实现数据展示。
2. 搭建后端接口(基于Express,新手友好)
步骤1:安装依赖
确保你的项目已初始化,执行以下命令安装必要工具:
npm init -y npm install express mssql
步骤2:改写index.js为后端接口
把你原来的SQL查询代码改成接口形式,让前端能通过HTTP请求获取数据:
const express = require('express'); const sql = require('mssql'); const app = express(); const port = 3000; // 替换成你的MS SQL实际配置 const sqlConfig = { user: '你的SQL用户名', password: '你的SQL密码', server: 'localhost', database: '你的数据库名', options: { encrypt: false, trustServerCertificate: true } }; // 定义获取数据的接口 app.get('/api/get-data', async (req, res) => { try { await sql.connect(sqlConfig); // 替换成你的表名,只查询id和name字段 const queryResult = await sql.query('SELECT id, name FROM 你的表名'); res.json(queryResult.recordset); // 返回JSON格式的数据 } catch (err) { console.error(err); res.status(500).json({ msg: '数据获取失败' }); } finally { await sql.close(); } }); // 启动后端服务 app.listen(port, () => { console.log(`后端服务运行在 http://localhost:${port}`); });
3. 编写前端HTML页面
创建index.html,通过fetch请求后端接口并渲染数据:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>SQL数据展示</title> </head> <body> <h2>数据列表</h2> <div id="dataContainer"></div> <script> // 页面加载完成后请求数据 window.addEventListener('load', async () => { try { const response = await fetch('http://localhost:3000/api/get-data'); if (!response.ok) throw new Error('请求失败'); const dataList = await response.json(); const container = document.getElementById('dataContainer'); // 循环渲染每条数据 dataList.forEach(item => { const itemDiv = document.createElement('div'); itemDiv.innerHTML = `<p>ID: ${item.id} | 名称: ${item.name}</p>`; container.appendChild(itemDiv); }); } catch (err) { console.error(err); alert('加载数据出错,请检查后端服务是否运行'); } }); </script> </body> </html>
4. 运行测试
- 启动后端服务:
node index.js
- 直接用浏览器打开
index.html,就能看到从MS SQL获取的id和name数据了。
内容的提问来源于stack exchange,提问作者Enderlith
相关产品推荐
相关产品推荐

