Home > Enterprise >  How to constantly send message from a node js to my front end
How to constantly send message from a node js to my front end

Time:03-09

How to constantly update my front end dashboard with new information from the back end. I have been searching for a solution online, but couldn't stumble on any.

I already know how to send static variables with ejs, but I cant figure out how to update my front end with new messages from the server.

I am working with express for the server and ejs for templating, plus server side java script.

I want to consonantly send messages to the user. Something like page 3 of 100......, 10 of 100..... and so forth. If you have experience with node Js, kindly help me out. Thanks.

CodePudding user response:

You could use Long pooling to solve your problem, Long pooling is,

  • A request is sent to the server

  • The server doesn’t close the connection until it has a message to send

  • When a message appears – the server responds to the request with it

  • The browser makes a new request immediately.

The situation when the browser sent a request and has a pending connection with the server is standard for this method. Only when a message is delivered, the connection is reestablished.

If the connection is lost, because of, say, a network error, the browser immediately sends a new request.A sketch of client-side subscribe function that makes long requests:

async function subscribe() {
  let response = await fetch("/subscribe");

  if (response.status == 502) {
    // Status 502 is a connection timeout error,
    // may happen when the connection was pending for too long,
    // and the remote server or a proxy closed it
    // let's reconnect
    await subscribe();
  } else if (response.status != 200) {
    // An error - let's show it
    showMessage(response.statusText);
    // Reconnect in one second
    await new Promise(resolve => setTimeout(resolve, 1000));
    await subscribe();
  } else {
    // Get and show the message
    let message = await response.text();
    showMessage(message);
    // Call subscribe() again to get the next message
    await subscribe();
  }
}

subscribe();

Hope this hepls!

  • Related