如何将Node.js中Azure SQL查询的数组数据传递至HTML用于Plotly.js可视化
我来帮你梳理几种实用的方案,把Node.js中从Azure SQL查询到的数组数据,传递给HTML页面里的Plotly.js来做可视化。这些方法都是前端和Node.js交互的常用手段,你可以根据自己的场景选:
如果你的需求只是快速做一个可视化Demo,用模板引擎直接把数据嵌入HTML是最省心的。这里以Express + EJS为例(EJS是最接近HTML的模板引擎,学习成本极低):
步骤1:初始化项目并安装依赖
打开终端,执行以下命令:
npm init -y npm install express ejs tedious @tediousjs/connection-pool
(tedious是连接Azure SQL的官方Node.js库,应该已经在你的项目里了对吧?)
步骤2:编写Node.js服务器代码(server.js)
const express = require('express'); const { Connection, Request } = require('tedious'); const app = express(); // 设置EJS为模板引擎 app.set('view engine', 'ejs'); app.set('views', './views'); // 模板文件统一放在views文件夹 // Azure SQL连接配置(替换成你的数据库信息) const config = { authentication: { options: { userName: '你的数据库用户名', password: '你的数据库密码' }, type: 'default' }, server: '你的服务器名.database.windows.net', options: { database: '你的数据库名', encrypt: true } }; // 路由:查询数据并渲染页面 app.get('/', (req, res) => { const connection = new Connection(config); const queryData = []; connection.on('connect', (err) => { if (err) { console.error(err); return res.send('数据库连接失败'); } // 执行查询(替换成你的SQL语句) const request = new Request('SELECT * FROM 你的目标表名', (err, rowCount) => { if (err) { console.error(err); return res.send('数据查询失败'); } connection.close(); // 把查询到的数组传给EJS模板 res.render('index', { chartData: queryData }); }); // 处理查询结果,组装成你需要的数组格式 request.on('row', (columns) => { const row = {}; columns.forEach(column => { row[column.metadata.colName] = column.value; }); queryData.push(row); }); connection.execSql(request); }); }); // 启动服务器 app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });
步骤3:编写EJS模板(views/index.ejs)
这个模板就是你的可视化页面,直接用<%= JSON.stringify(chartData) %>把Node.js里的数组转成前端能识别的JSON:
<!DOCTYPE html> <html> <head> <title>Azure SQL数据可视化</title> <!-- 引入Plotly.js --> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="chart" style="width: 800px; height: 600px;"></div> <script> // 直接拿到Node.js传过来的数组数据 const data = <%= JSON.stringify(chartData) %>; // 处理数据成Plotly需要的格式(根据你的数据结构调整字段名) const trace = { x: data.map(item => item.日期字段名), // 替换成你的X轴数据字段 y: data.map(item => item.数值字段名), // 替换成你的Y轴数据字段 type: 'bar' // 可以换成line、scatter等图表类型 }; // 渲染图表 Plotly.newPlot('chart', [trace]); </script> </body> </html>
运行
执行node server.js,然后打开浏览器访问http://localhost:3000就能看到可视化图表了!
如果以后你想扩展成更复杂的应用(比如实时更新数据、多页面交互),这种前后端分离的方式更灵活:
步骤1:修改Node.js服务器(server.js)
新增一个API路由返回JSON数据,同时托管静态HTML文件:
const express = require('express'); const { Connection, Request } = require('tedious'); const app = express(); // 托管静态文件(HTML、CSS、JS都放在public文件夹) app.use(express.static('public')); // Azure SQL配置和之前一致,这里省略... // API路由:返回查询到的JSON数据 app.get('/api/data', (req, res) => { const connection = new Connection(config); const queryData = []; connection.on('connect', (err) => { if (err) { console.error(err); return res.status(500).json({ error: '数据库连接失败' }); } const request = new Request('SELECT * FROM 你的目标表名', (err, rowCount) => { if (err) { console.error(err); return res.status(500).json({ error: '数据查询失败' }); } connection.close(); res.json(queryData); // 返回JSON格式的数据 }); request.on('row', (columns) => { const row = {}; columns.forEach(column => { row[column.metadata.colName] = column.value; }); queryData.push(row); }); connection.execSql(request); }); }); app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });
步骤2:编写静态HTML文件(public/index.html)
在HTML里用fetch请求API拿到数据,再传给Plotly:
<!DOCTYPE html> <html> <head> <title>Azure SQL数据可视化</title> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="chart" style="width: 800px; height: 600px;"></div> <script> // 从API接口获取数据 fetch('/api/data') .then(response => response.json()) .then(data => { // 处理数据并渲染图表 const trace = { x: data.map(item => item.日期字段名), y: data.map(item => item.数值字段名), type: 'line' }; Plotly.newPlot('chart', [trace]); }) .catch(err => console.error('获取数据失败:', err)); </script> </body> </html>
运行方式和之前一样,访问http://localhost:3000即可看到效果。
如果你的数据不需要实时更新,只想生成一个静态HTML文件直接打开用,可以让Node.js直接把数据写入HTML:
编写Node.js脚本(generate-chart.js)
const fs = require('fs'); const { Connection, Request } = require('tedious'); // Azure SQL配置,这里省略... const connection = new Connection(config); const queryData = []; connection.on('connect', (err) => { if (err) { console.error(err); return; } const request = new Request('SELECT * FROM 你的目标表名', (err, rowCount) => { if (err) { console.error(err); return; } connection.close(); // 读取HTML模板文件 fs.readFile('template.html', 'utf8', (err, html) => { if (err) { console.error(err); return; } // 替换模板里的占位符为查询到的数据 const finalHtml = html.replace('{{CHART_DATA}}', JSON.stringify(queryData)); // 生成最终的静态HTML文件 fs.writeFile('chart.html', finalHtml, (err) => { if (err) { console.error(err); } else { console.log('静态HTML文件已生成:chart.html'); } }); }); }); request.on('row', (columns) => { const row = {}; columns.forEach(column => { row[column.metadata.colName] = column.value; }); queryData.push(row); }); connection.execSql(request); });
编写HTML模板(template.html)
<!DOCTYPE html> <html> <head> <title>Azure SQL数据可视化</title> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="chart" style="width: 800px; height: 600px;"></div> <script> const data = {{CHART_DATA}}; const trace = { x: data.map(item => item.日期字段名), y: data.map(item => item.数值字段名), type: 'scatter' }; Plotly.newPlot('chart', [trace]); </script> </body> </html>
运行
执行node generate-chart.js,生成chart.html后,直接双击打开就能看到图表了!
这三种方法覆盖了从快速Demo到可扩展应用的场景,你可以根据自己的需求选。如果还有细节不清楚,比如数据格式怎么调整适配Plotly,随时问就行~
内容的提问来源于stack exchange,提问作者I'l Follio

