Home > Blockchain >  Updating API response to GET request with node js express
Updating API response to GET request with node js express

Time:10-09

I am a web development noob. I am building a web app in node js express, and I am able to populate a route with a dummy json. I don't want to use a database but just have live data being updated every few seconds.

app.route('/robot-data').get( async (req, res) => {
    res.json([ // dummy data
        {"data":0},
    ]);
});

My html is able to read from this API fine. The problem is, I would like to update the response, eventually with an emit event but for testing I am trying to just do it periodically.

let dataSource = 0;
const updateDataSource = () => {
  const delta = Math.random();
  dataSource  = delta;
  app.get('/robot-data', (req, res) => {
      res.json([
        // updated data
      ]);
    });
}

const PORT = process.env.PORT || 8080;
app.listen(PORT, _ => {
    setInterval(()=> updateDataSource(), 3000);
});

However, when I run this the json at the endpoint doesn't change when I refresh. Basically, I want to have what is happening at this api for my json. https://api.wheretheiss.at/v1/satellites/25544

I've looked into websockets etc but I really just want to do what the ISS api is doing.

CodePudding user response:

Your code executes the statement app.get('/robot-data', (req, res) => {...}) repeatedly, which does not work. Middleware functions like (req, res) => {...} must be set up only once, and if their behaviour shall change over time, they can refer to variables defined outside of them, and these variables can change.

In your case, this would look so:

let dataSource = 0;
const updateDataSource = () => {
  const delta = Math.random();
  dataSource  = delta;
};
app.get('/robot-data', (req, res) => {
  res.json([
    {"data":dataSource}
  ]);
});
  • Related