1

I am using the fetch api to get data from backend. The data I am getting is dynamic and more and more data keeps producing. What I want is to send the data to the front end when I get the data in the backend. How can I achieve this? I have coded a sample example of my senario below. Thanks in advance

fetch('/api/blah', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      request: `{"requestType": "numbers"}`
    })
  })
  .then((res) => res.json())
  .then(data => {
    if (data.status == 'success') {
      const numbers = data.numbers
      console.log(numbers)
    }
  });

const distribution = async(req, res) => {
  const request = JSON.parse(req.body.request)
  if (request.requestType == 'numbers') {
    var ceiling = 100;
    var floor = 1;
    var x = 1;
    var step = 1;

    setInterval(function() {
      res.send({
        status: 'success',
        numbers: x
      })
      x += step;
      if (x === ceiling || x === floor) {
        step = -step;
      }
    }, 500);
  }
}

1
  • WebSockets or Server Sent Events Commented Sep 22, 2022 at 10:27

4 Answers 4

2

You can use sockets to get your desired output. You can follow this link for more info Send message to specific client with socket.io and node.js

     const
            {Server} = require("socket.io"),
            server = new Server(8000);
        
      var ceiling = 100;
        var floor = 1;
        var x = 1;
        var step = 1;
        
        let
            sequenceNumberByClient = new Map();
        
        // event fired every time a new client connects:
        server.on("connection", (socket) => {
            console.info(`Client connected [id=${socket.id}]`);
            // initialize this client's sequence number
            sequenceNumberByClient.set(socket, 1);
        
            // when socket disconnects, remove it from the list:
            socket.on("disconnect", () => {
                sequenceNumberByClient.delete(socket);
                console.info(`Client gone [id=${socket.id}]`);
            });
        });
        
        //emit your data to specific channel
        setInterval(function() {
  for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
           client.emit("numbers", x);
          x += step;
          if (x === ceiling || x === floor) {
            step = -step;
          }
}
        }, 500);
Sign up to request clarification or add additional context in comments.

5 Comments

then how do I access numbers on client side?
check the link i referred they provide client and server side implementation
you can also use this simple chat example and use it in your code with little modifications socket.io/get-started/chat
how can I allow cors with your code?
you can use cors package for express like => app.use(cors())
1

For passing data from the back-end to the front-end dynamically, you can use jQuery AJAX

https://www.w3schools.com/js/js_ajax_intro.asp

In your case, you can call the AJAX endpoint once every few minutes or so to get the new data.

1 Comment

I can do that with fetch too but that's not the solution Im looking for
0

In REST API structure you can send a response to an API only once. You cannot use setInterval to generate multiple response. instead you should add all possible data in array and put that array in your response once.

const distribution = async (req, res) => {

  const request = JSON.parse(req.body.request);

  if (request.requestType == "numbers") {

    var ceiling = 100;
    var step = 1;
    var return_arr = [];

    for (let i = 1; i <= ceiling; i += step) {
      return_arr.push(i);
    }

    res.send({
      status: "success",
      numbers: return_arr,
    });
  }
};

4 Comments

My data is dynamic and I need the data as soon as I got it in the backend
can you please explain it in detail?
if you want to get data dynamic from the server then you can use sockets
say my celling is 2000 I can't wait until 2000 is reached I need to access the data in front end as soon as I get it in the back end
0

If I understand correctly you want to send server events from your server to your frontend as soon as data changes on the server. In order to achieve this you will need websocket connections from frontend to server. websockets are a bidirectional connection between your server and client. while the clients are connected to the server via sockets, the server can send events to the frontend without receiving a request first. I suggest using socket.io for this.

You can find more info about socket.io here: https://socket.io/docs/v4/

There are more alternatives like the websocketAPI. more info about websocketAPI you can find in mozilla webdocs here: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

Also I found this article on how to implement websockets without socket.io as socket.io is more like a framework on top of normal websockets: https://www.piesocket.com/blog/nodejs-websocket

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.