Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

express - How to evaluate API response from server and act accordingly at client side using Fetch() and Node.js

I fetch data at server side and push the result to global variable and then send that global variable to client with app.post method using Express.js. My problem is that client fetches the global variable too soon without the data received from the API first. How can I evaluate the response so that client would wait the global variable to reveive data first before displaying anything.

Server side, code looks something like this:

let sharpe = ''
app.post('/api', async(req, res, next) => {
  console.log('I got a request!')
  thisOne = req.body.stock1
  thisOne2 = req.body.stock2

  var result = await setup();

  res.json({
    status: 'success',
    stocks: sharpe
  });

})

Sharpe is the global variable storing the response from multiple API calls and is the one that should be sent back to client. Client side code is this:

  const sendData =  async (event) => {
    event.preventDefault();
    var stock1 = document.getElementById('weight1').value
    var stock2 = document.getElementById('weight2').value

    const data = {stock1, stock2};
    const options = {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {'Content-Type': 'application/json' }
    }

    fetch('/api', options).then(res => res.json()).then(res => {

      console.log(res.stocks);

    })
  

}

As a result SendData() function fetches the sharpe variable that is empty at the moment. How can I adjust client side code or server side code that the client waits for a correct response? Thanks.

One solution would be to store the API results to database and client would fetch ready made datastream but is there more straightforward solution?

question from:https://stackoverflow.com/questions/65869879/how-to-evaluate-api-response-from-server-and-act-accordingly-at-client-side-usin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To wait for your API Server to set the sharpe Parameter, it needs to be awaited, which you already did. It depends on the setup function (for example setup()) which fills the sharpe parameter. It has to return a promise, which is resolved once sharpe is filled with the data.

let sharpe = ''

async setup() {
  return new Promise((resolve, reject) => {
    sharpe = 'test';
    // set value for sharpe
    resolve()
  })
}


app.post('/api', async(req, res, next) => {
  console.log('I got a request!')
  thisOne = req.body.stock1
  thisOne2 = req.body.stock2

  var result = await setup();

  res.json({
    status: 'success',
    stocks: sharpe
  });

})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...