Node.JS Server Sent Events: Route continues to run after res.end() resulting in ERR_STREAM_WRITE_AFTER_END error

后端 未结 1 1549
走了就别回头了
走了就别回头了 2021-01-16 09:02

I am getting started with Server Sent Events (SSE) since my web app requires receiving real time updates from the server. It does not require sending anything to the server,

相关标签:
1条回答
  • 2021-01-16 10:03

    When the stream closes, you need to remove your event listener so you won't try to write to the stream again. That could be done like this:

    router.get('/updates', (req, res) => {
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
        });
    
        function listener(event) {
            console.log('Event triggered! Sending response.');
            res.write('data: Event triggered!\n\n');
        }
    
        // Listens for 'event' and sends an 'Event triggered!' message to client when its heard.
        eventEmitter.addListener('event', listener);
    
        req.on('close', () => {
            // remove listener so it won't try to write to this stream any more
            eventEmitter.removeListener('event', listener);
            console.log('Connection to client closed.');
            res.end();
        });
    });
    
    module.exports = router;
    

    FYI, I don't think you need the res.end() when you've already received the close event. You would use res.send() if you were unilaterally trying to close the connection from the server, but if it's already closing, I don't think you need it and none of the code examples I've seen use it this way.

    I wonder if it's possible that your res.end() is also why you're getting two close events. Try removing it.

    0 讨论(0)
提交回复
热议问题