Home > Blockchain >  send multiple data from backend to front end
send multiple data from backend to front end

Time:09-22

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);
  }
}

CodePudding user response:

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);

CodePudding user response:

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.

CodePudding user response:

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,
    });
  }
};

CodePudding user response:

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

  • Related