如何在express.js中使用server-sent-events [英] How to use server-sent-events in express.js

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

问题描述

我使用 express.js 设置我的REST服务器。现在我想将sse添加到此服务器。在我实施这个 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.

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

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