Node.js Express如何将函数返回值转为JSON并实现无刷新每秒更新
问题根因
常规HTTP协议是请求-响应的单次交互模式,你发起一次页面请求,服务端只能返回一次固定的res.json结果,后台的setTimeout循环只是在服务端本地计算数值,不会主动把新数据推送给浏览器,所以必须刷新页面重新发起请求才能拿到更新后的值。
解决方案:使用Server-Sent Events(SSE)实现服务端主动推送
SSE是HTML5原生支持的服务端单向推送协议,正好匹配你需要服务端每秒主动给浏览器推新数值的需求,实现成本极低,不需要额外引入第三方依赖。
完整服务端代码
// Import packages const express = require("express"); const app = express(); const port = 8000; // 允许静态文件访问,用来放前端测试页面 app.use(express.static('public')); // SSE推送接口 app.get("/stream", (req, res) => { // 设置SSE必要响应头 res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); res.setHeader('Access-Control-Allow-Origin', '*'); // 每秒生成随机数推送 const sendInterval = setInterval(() => { const random = Math.round(Math.random() * (3000 - 500)) + 500; // SSE推送格式要求:data: 开头,两个换行结束一次推送 res.write(`data: ${JSON.stringify({ random: random })}\n\n`); }, 1000); // 客户端断开连接时清除定时器,避免内存泄漏 req.on('close', () => { clearInterval(sendInterval); res.end(); }); }); // Starting server app.listen(port, () => console.log(`listening on port ${port}!`));
前端测试页面代码
在项目根目录新建public文件夹,里面创建index.html,内容如下:
<!DOCTYPE html> <html> <body> <h1>实时随机数:<span id="randomNum"></span></h1> <script> // 连接SSE接口 const eventSource = new EventSource('/stream'); // 监听服务端推送的消息 eventSource.onmessage = (event) => { const data = JSON.parse(event.data); document.getElementById('randomNum').textContent = data.random; }; // 监听错误 eventSource.onerror = (err) => { console.error('SSE连接错误:', err); eventSource.close(); }; </script> </body> </html>
效果验证
启动服务后访问http://localhost:8000,不需要刷新页面,数值就会每秒自动更新。
如果不需要前端页面,只是想接口直接返回流式数据,直接访问http://localhost:8000/stream也能看到每秒更新的JSON数据。
内容的提问来源于stack exchange,提问作者kim tech
相关产品推荐
相关产品推荐

