【问题标题】:Responding to a HTTP Get with an SSE使用 SSE 响应 HTTP Get
【发布时间】:2012-07-06 06:20:17
【问题描述】:

我正在试验 HTML5 和 node.js。我已经测试了服务器发送事件,它们运行良好(参考this example)。

接下来,我尝试使用 SSE 回复按钮按下。在按下“增量”按钮时,我从文本框中选择一个数字并使用 GET 消息将其传递给服务器。然后服务器将响应一个包含递增数字的事件。然后 eventListener 将使用接收到的数字更新文本框。我还在 HTML 页面上添加了一个“消息区域”来记录消息。

这就是计划。但是,当我单击该按钮时,浏览器会在窗口底部显示“正在下载”操作,但它从未完成,结果不会在屏幕上更新,消息也不会显示在页面底部。

当我在页面加载时发送它们时,这些事件工作正常。但是当我发送它以响应 GET 消息时,HTML 页面没有显示任何响应。

这里是 HTML 部分。

<form action="/upload" method="get">
<p>Set the temperature and click on send</p>
<input name="temperature" id="TemperatureBox" type="text" value = "33" />
<button type="submit" onclick="form.action='http://localhost:8888/Increment'">Increment</button>

我为消息和“温度事件”添加了处理程序,它将更新温度框

var source = new EventSource('/events');

source.addEventListener('message', function(e) {
  //code to display message
}, false);

source.addEventListener('TemperatureValueUpdate', function(e) {
        AddLog('TemperatureValueUpdate Listener >> lastEventID: ' + (e.lastEventId || '--') +
               ', e.data: ' + e.data
        + 'Current value of text box: ' +  document.getElementById('TemperatureBox').value);
        document.getElementById('TemperatureBox').value= e.data;

}, false);

在 node.js 脚本中,我发送一条消息和一个 TemperatureValueUpdate

function constructTemperature(response, id, data) {
console.log("Sending Temperature event");
//  response.write('id: ' + (new Date()).toLocaleTimeString()+ '\n');
 // response.write("data: " + 'Teperature event sent '+ '\n\n');

response.write('event: ' + 'TemperatureValueUpdate' + '\n');
response.write('id: ' + id + '\n');
response.write("data: " + data + '\n\n');

console.log("Finished Temperature event"); }

我还回复了页面加载时的“/events”网址,回复为 200:

response.writeHead(200, {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache', 'Connection': 'keep-alive' });

我什至尝试过以下方法

  • 在发送事件之前发送 202/204 响应
  • 在发送事件之前/之后发送 response.end()
  • 在每个事件之前发送“Content-Type”:“text/event-stream”

但它们不会产生预期的结果。我在这里做错了什么?

【问题讨论】:

    标签: html node.js server-sent-events


    【解决方案1】:

    听起来您在提交表单时正在调用constructTemperature() 函数。如果是这种情况,您与 EventSource 的连接不同。因此,您需要将数据存储在服务器上的某个位置返回给客户端,并在源自 EventSource 的请求中调用constructTemperature()。

    【讨论】:

    • 让我看看我是否理解。当我启动页面时,网址是http://localhost:8888//MyApp,当我按下按钮时,发送的网址是http://localhost:8888/Increment?temperature=33。通过不同的连接,您的意思是说我的路径名应该在整个应用程序中保持不变?因此,为了增加数字,我应该使用 http://localhost:8888//MyApp?operation=Increment&amp;temperature=33 之类的东西,而不是当前的。
    • 不完全。 EventSource 正在寻找事件的 URL 是 http://localhost:8888/events。来自该 URL 的响应应该包含来自 constructTemperature() 函数的响应。
    • 我尝试将所有 HTTP 请求的 url 更改为 http://localhost:8888/MyApp 并将事件源注册为 var source = new EventSource('/MyApp');。我根据 `req.headers.accept =='text/event-stream' 条件进行区分;唯一的区别是浏览器不会永远显示下载框,但问题仍然存在。
    猜你喜欢
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 2011-04-08
    相关资源
    最近更新 更多