我正在试验HTML5和node.js.我已经测试了服务器发送的事件并且它们工作正常(参考this example)。响应HTTP获取SSE
接下来我试着回复一个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"); }
我也回应了pag上的“/ events”网址用200回复ë负载:
response.writeHead(200, {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache', 'Connection': 'keep-alive' });
我甚至尝试了以下
- 之前发送所述事件
- 发送到Response.End(之前发送响应202/204)/发送后事件
- 发送“内容类型”:每个事件
前“文/事件流”但他们不产生DES结果。我在这里做错了什么?
让我看看我是否理解。当我启动页面时,url是'http:// localhost:8888 // MyApp',当我按下按钮时,发送的URL是'http:// localhost:8888/Increment?temperature = 33'。通过不同的连接,你的意思是说我的路径名应该在整个应用程序中保持一致吗?因此,为了递增数字,我应该使用'http:// localhost:8888 // MyApp?operation = Increment&temperature = 33'而不是当前的。 – DPD 2012-07-06 07:34:54
不完全。 EventSource查找事件的URL是'http:// localhost:8888/events'。该URL的响应应该包含'constructTemperature()'函数的响应。 – Maurice 2012-07-06 07:59:31
我尝试将所有HTTP请求的URL更改为'http:// localhost:8888/MyApp',并将事件源注册为'var source = new EventSource('/ MyApp');'。我根据'req.headers.accept =='text/event-stream'条件区分;唯一的区别是浏览器不会永久显示下载框,但问题仍然存在。 – DPD 2012-07-09 09:03:09