PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] How to send server sent events on database update

 October 20, 2022     javascript, node.js, server-sent-events, sockets     No comments   

Issue

I want to send SSE event only when there is a DB update API called. How do I achieve this? What is the standard market practise to achieve this?

my SSE endpoint looks like this

app.get('/send-events', (req, res) => {
    const headers = {
        Connection: "keep-alive",
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
    };
    res.writeHead(200, headers);

    const data = `data: ${new Date()}\n\n`;

    res.write(data);
});

i want to trigger the above api when another api is being called. Eg below

app.post('/update-db', (req, res) => {
    res.send('db-updated');

    //perform db update
    //send the latest data thru sse endpoint
});

Solution

It seems by default SSE doesn't work with multiple clients/browser tabs. In order to achieve that we have to send the event to all the clients that are currently connected/listening to the server

This code sample solves my problem

https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app#step-2-testing-the-backend



Answered By - Kallol Medhi
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing