如何在 express.js 中使用服务器发送的事件 [英] How to use server-sent-events in express.js

查看:28
本文介绍了如何在 express.js 中使用服务器发送的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 express.js 设置了我的 REST 服务器.现在我想将 sse 添加到此服务器.在我实施 this sse 包后,出现错误.我知道我收到这个错误,什么时候会尝试使用 res.send 两次,但我没有.

I setup my REST server with express.js. Now I want to add sse to this server. After I implemented this sse package, I get an error. I know that I get this error, when would try to use res.send twice, but I am not.

ERROR: Error: Can't set headers after they are sent.                                            
    at ServerResponse.OutgoingMessage.setHeader (http.js:690:11)                            
    at ServerResponse.header (/home/root/node_modules/express/lib/response.js:718:10)         
    at ServerResponse.send (/home/root/node_modules/express/lib/response.js:163:12)            
    at app.get.str (/home/root/.node_app_slot/main.js:1330:25)                                 
    at Layer.handle [as handle_request] (/home/root/node_modules/express/lib/router/layer.js:95:5)    
    at next (/home/root/node_modules/express/lib/router/route.js:131:13)                       
    at sse (/home/root/node_modules/server-sent-events/index.js:35:2)                          
    at Layer.handle [as handle_request] (/home/root/node_modules/express/lib/router/layer.js:95:5)  
    at next (/home/root/node_modules/express/lib/router/route.js:131:13)                          
    at Route.dispatch (/home/root/node_modules/express/lib/router/route.js:112:3)

我是否可能无法在 sse 函数中再使用 express 方法?例如:

Is it possible that I can't use the express methods anymore within the sse function? For example:

app.get('/events', sse, function(req, res) {
    res.send('...');
});

此外,我发现了这个解决方案和这个.是否可以使用 res.write 函数或以其他方式制作 sse 而不使用其他包?

Furthermore, I found this solution and this. Is it possible to make sse with the res.write function or in another way without using another package?

推荐答案

你绝对可以在没有其他包的情况下实现这一点.

You can definitely achieve this without other packages.

我写了一篇关于这个的博客文章,第 1 部分 列出了基础知识.

I wrote a blog post about this, part 1 sets out the basics.

您不得关闭 SSE,因为这会破坏功能.重点是它是一个开放的 HTTP 连接.这允许随时将新事件推送到客户端.

You mustn't close the SSE as that breaks the functionality. The whole point is that it is an open HTTP connection. This allows for new events to be pushed to the client at any point.

这篇关于如何在 express.js 中使用服务器发送的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆