Node+Express实现每秒自动刷新时间的原生方案咨询
原生Node.js + Express 实现时区时间实时更新方案
下面提供两种无需第三方库(如socket.io)的原生实现方案,适配你的时区时间展示需求:
方案一:前端定时轮询API
通过前端setInterval每秒请求后端接口获取最新时间,实现秒级更新,实现成本极低。
后端Express实现
const express = require('express'); const app = express(); const port = 3000; // 提供指定时区的时间接口 app.get('/api/time/:timezone', (req, res) => { const timezone = req.params.timezone; try { // 生成指定时区的格式化时间 const currentTime = new Date().toLocaleString('zh-CN', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); res.json({ time: currentTime }); } catch (err) { res.status(400).json({ error: '无效时区,请使用如Asia/Shanghai格式' }); } }); // 托管前端静态页面 app.use(express.static('public')); app.listen(port, () => { console.log(`服务器运行在 http://localhost:${port}`); });
前端页面实现(public/index.html)
<!DOCTYPE html> <html> <head> <title>时区实时时间</title> </head> <body> <h2>指定时区时间:<span id="timeEl"></span></h2> <script> const targetTimezone = 'Asia/Shanghai'; // 可替换为用户指定时区 const timeEl = document.getElementById('timeEl'); // 更新时间的核心函数 function fetchAndUpdateTime() { fetch(`/api/time/${targetTimezone}`) .then(res => res.json()) .then(data => timeEl.textContent = data.time) .catch(err => console.error('更新时间失败:', err)); } // 初始化加载+每秒自动更新 fetchAndUpdateTime(); setInterval(fetchAndUpdateTime, 1000); </script> </body> </html>
方案二:Server-Sent Events(SSE)服务器主动推送
利用原生SSE协议实现服务器向客户端单向推送时间,相比轮询减少重复HTTP请求开销,更适合实时场景。
后端Express实现
const express = require('express'); const app = express(); const port = 3000; // SSE实时时间推送接口 app.get('/sse/time/:timezone', (req, res) => { // 设置SSE专属响应头 res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); res.flushHeaders(); // 立即发送响应头 const timezone = req.params.timezone; // 每秒推送一次时间 const pushInterval = setInterval(() => { try { const currentTime = new Date().toLocaleString('zh-CN', { timeZone: timezone, hour: '2-digit', minute: '2-digit', second: '2-digit' }); // SSE数据格式:data: 内容\n\n res.write(`data: ${JSON.stringify({ time: currentTime })}\n\n`); } catch (err) { clearInterval(pushInterval); res.end(); } }, 1000); // 客户端断开连接时清理定时器 req.on('close', () => { clearInterval(pushInterval); res.end(); }); }); // 托管前端静态页面 app.use(express.static('public')); app.listen(port, () => { console.log(`服务器运行在 http://localhost:${port}`); });
前端页面实现(public/index.html)
<!DOCTYPE html> <html> <head> <title>SSE时区实时时间</title> </head> <body> <h2>指定时区时间:<span id="timeEl"></span></h2> <script> const targetTimezone = 'Asia/Shanghai'; const timeEl = document.getElementById('timeEl'); // 建立SSE连接 const sse = new EventSource(`/sse/time/${targetTimezone}`); // 接收服务器推送的时间 sse.onmessage = (event) => { const data = JSON.parse(event.data); timeEl.textContent = data.time; }; // 处理连接错误 sse.onerror = (err) => { console.error('SSE连接异常:', err); sse.close(); }; </script> </body> </html>
内容的提问来源于stack exchange,提问作者kimo02
相关产品推荐
相关产品推荐

