Simple Way to Implement Server Sent Events in Node.js?

前端 未结 6 1406
南方客
南方客 2021-01-31 06:11

I\'ve looked around and it seems as if all the ways to implement SSEs in Node.js are through more complex code, but it seems like there should be an easier way to send and recei

6条回答
  •  渐次进展
    2021-01-31 06:44

    If you're using express this is the easiest way https://www.npmjs.com/package/express-sse

    on BE:

    const SSE = require('express-sse');
    
    const sse = new SSE();
    
    ...
    
    app.get('/sse', sse.init);
    
    ...
    
    sse.send('message', 'event-name');
    

    on FE:

    const EventSource = require('eventsource');
    
    const es = new EventSource('http://localhost:3000/sse');
    
    es.addEventListener('event-name', function (message) {
      console.log('message:', message)
    });
    

提交回复
热议问题