Server-Sent Events with Express

Server-Sent Events with Express

Server-Sent Events with Express

In this post, we will give you information about Server-Sent Events with Express – onlinecode. Here we will give you detail about Server-Sent Events with Express – onlinecode And how to use it also give you a demo for it if it is necessary

Server-sent events are a new HTTP API for pushing events from the server to the client. Unlike websockets, server-sent events (SSE for short) are built
on top of the HTTP protocol, so no need for ws:// URLs or additional npm modules.
Server-side events also handle reconnecting automatically, so you don’t have to write
code to reconnect if the connection is lost.

Getting Started

On the client side, you use the EventSource class to connect to a server-side event source.
The client side is easy: just point the EventSource class to an Express route that’s configured to handle SSE and add an event listener.

<html>
  <body>
    <div id="content"></div>

    <script type="text/javascript">
      const source = new EventSource('/events');

      source.addEventListener('message', message => {
        console.log('Got', message);

        // Display the event data in the 'content' div
        document.querySelector('#content').innerHTML = event.data;
      });
    </script>
  </body>
</html>

The Express side is the tricky part. To support SSE, you need to
set 3 headers, and then send the headers to the client using flushHeaders():

  • Cache-Control: no-cache
  • Content-Type: text/event-stream: So the client knows this response is an HTTP stream
  • Connection: keep-alive: So Node.js knows to keep the HTTP socket open

Once you’ve called flushHeaders(), you can then start writing events using the res.write() function. The res.write() function
writes to the HTTP connection without explicitly ending the HTTP response. Make sure you do not use res.send() or res.end(), because those explicitly end the response.

Below is an example of a standalone Express server that handles SSE with the
/events endpoint:

'use strict';

const express = require('express');
const fs = require('fs');

run().catch(err => console.log(err));

async function run() {
  const app = express();

  app.get('/events', async function(req, res) {
    console.log('Got /events');
    res.set({
      'Cache-Control': 'no-cache',
      'Content-Type': 'text/event-stream',
      'Connection': 'keep-alive'
    });
    res.flushHeaders();

    // Tell the client to retry every 10 seconds if connectivity is lost
    res.write('retry: 10000nn');
    let count = 0;

    while (true) {
      await new Promise(resolve => setTimeout(resolve, 1000));

      console.log('Emit', ++count);
      // Emit an SSE that contains the current 'count' as a string
      res.write('data: ${count}nn');
    }
  });

  const index = fs.readFileSync('./index.html', 'utf8');
  app.get('/', (req, res) => res.send(index));

  await app.listen(3000);
  console.log('Listening on port 3000');
}

Run the above server and navigate to http://localhost:3000, you
should see the below:



Want to become your team’s Express expert? There’s no better way to really grok a framework than to write your own
clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express
called Espresso.
Get your copy!

Espresso supports:

  • Route handlers, like ‘app.get()’ and ‘app.post()’
  • Express-compatible middleware, like ‘app.use(require(‘cors’)())’
  • Express 4.0 style subrouters

As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

I need more information on what you are looking for. Here are a few options for what you might mean by ‘express’:

  • Express train: A train that makes fewer stops than a regular train, and therefore travels faster.
  • Express delivery: A service that delivers packages quickly, usually within 24 hours.
  • Express yourself: To communicate your thoughts and feelings in a clear and direct way.
  • Express lane: A lane on a highway that is reserved for cars that are traveling faster than the other lanes.
  • Expresso: A strong, concentrated coffee.

Please let me know if any of these are what you were looking for. If not, please provide more information so I can better assist you.

Here are some examples of how to use the word ‘express’ in a sentence:

  • I took the express train to work today.
  • I ordered the package to be delivered express.
  • She expressed her anger by slamming the door.
  • The express lane was moving much faster than the other lanes.
  • I love the strong taste of espresso.

Hope this code and post will helped you for implement Server-Sent Events with Express – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US