乐闻世界logo
搜索文章和话题

How to pass POST parameters with HTML SSE?

1 个月前提问
1 个月前修改
浏览次数12

1个答案

1

在HTML5中,SSE(Server-Sent Events)是一种允许服务器主动向客户端发送信息的技术。通常,SSE用于创建到服务器的单向连接,服务器可以通过这个连接发送更新到客户端。

但是,SSE的标准实现并不直接支持发送POST请求,因为SSE基于HTTP GET方法。如果你需要在建立SSE连接时发送数据(例如,初始化参数),你通常需要在建立连接时将这些数据作为查询参数(query parameters)附加在URL后面。

示例:

假设你需要传递用户ID和某种类型的订阅信息来初始化SSE连接。你可以这样做:

html
<!DOCTYPE html> <html> <body> <script> // 假设 userId 和 subscriptionType 已经通过某种方式获取 var userId = 'user123'; var subscriptionType = 'news_update'; // 创建一个新的EventSource对象,并在URL中包含必要的查询参数 var source = new EventSource(`http://example.com/events?userId=${encodeURIComponent(userId)}&subscriptionType=${encodeURIComponent(subscriptionType)}`); source.onmessage = function(event) { console.log("Received data: ", event.data); }; source.onerror = function(error) { console.error("EventSource failed:", error); source.close(); }; </script> </body> </html>

处理服务器端:

在服务器端,你需要解析这些查询参数,并根据它们来决定发送什么数据给客户端。这里是一个使用Node.js和Express框架的简单例子:

javascript
const express = require('express'); const app = express(); app.get('/events', function(req, res) { const userId = req.query.userId; const subscriptionType = req.query.subscriptionType; // 设置必要的头部信息以启用SSE res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', }); const sendData = () => { const data = `Date: ${new Date()}`; res.write(`data: ${data}\n\n`); }; // 每秒发送一次数据 const intervalId = setInterval(sendData, 1000); req.on('close', () => { clearInterval(intervalId); res.end(); }); }); app.listen(3000, () => console.log('SSE server started on port 3000'));

总结:

虽然你不能直接通过SSE发送POST请求,但你可以通过在请求的URL中包含查询参数的方式来传递初始化数据。服务器可以读取这些参数并据此提供个性化的数据流。

2024年8月15日 20:29 回复

你的答案