Home > Mobile >  Is It possible to call request with setInterval?
Is It possible to call request with setInterval?

Time:10-17

I'm new to node.js

I'm trying to call API with header every x seconds in node.js , And what i achieve is like

  1. type some information of header for getting external API from client and post it to my backend server.
  2. get data from External data which keeps changing data any second ,
  3. call external API from backend server every seconds and send it to client.
  4. get data from my backend server to client, and the data keep changing.

I'm not sure if the way I'm doing is okay .

, So, i tried to do like this:

In Node.js

app.post("/realtime", (req, res) => {

  var url = req.body.GET_API_URL;
  var header1_key = req.body.Headers1_key;
  var header1_value = req.body.Headers1_Value;
  var header2_key = req.body.Headers2_key;
  var header2_value = req.body.Headers2_Value;
  var header3_key = req.body.Headers3_key;
  var header3_value = req.body.Headers3_Value;

  var option = {

    url: url,
    method: "GET",
    headers: {
      [header1_key]: header1_value,
      [header2_key]: header2_value,
      [header3_key]: header3_value,
    },
  };

  const interval = () => {
    request(option, (error, response, body) => {
      try {
        res.json(JSON.parse(body));
      } catch (error) {}
    });
  };
  setInterval(interval, 1000);

});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

in client

  function getAPI() {
      axios
        .post("http://localhost:5000/realtime", {
          GET_API_URL: convert.GET_API_URL,
          Headers1_key: convert.Headers1_key,
          Headers1_Value: convert.Headers1_Value,
          Headers2_key: convert.Headers2_key,
          Headers2_Value: convert.Headers2_Value,
          Headers3_key: convert.Headers3_key,
          Headers3_Value: convert.Headers3_Value,
        })
        .then(response => {
          setRandom(response.data);
          console.log(response);
          
        })
        .catch(error => {
          console.log(error);
        });
   
  }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>


it doesn't get any error and it's didn't work as i expected.

So i wonder if what i do is right way to do or is complete wrong . And if It's wrong I'd like to get advice . if there is alternative to achieve it, i'd really appreciate it. Thank you in advance

CodePudding user response:

You can use Promise in javascript

function intervalAPI = async () =>  {
    return new Promise((done, reject) => {
        setIntrrval(() => {
            conse { data } = await axios(...);
            done(data);
        }, 1000);
    }
}

Promise Docs

  • Related