Friday, October 14, 2022

[FIXED] How can I use axios result in res.render in expressjs?

Issue

I don't know how I can use axios response.data in "res.render" in expressjs, I tried to create an Array and transfer axios result into a new array (myWorkspace) and then use Array globally but Array is empty!!

app.get('/fullscreen', passport.isAuthenticated, passport.isAuthorized('user'), (req, res) => {
  var myWorkspace = [];

  axios
    .get('http://localhost:8080/geoserver/rest/workspaces', {
      auth: {
        username: 'admin',
        password: '@dmin9901',
      },
      headers: {
        accept: 'application/json',
        'content-type': 'application/json',
      },
    })
    .then(function(response) {
      myWorkspace.push(response.data['workspaces']);
      return myWorkspace;
    })
    .catch(function(error) {
      // handle error
      console.log(error);
    })
    .then(function() {
      // always executed
    });

  res.render('fullscreen', {
    workspace: JSON.stringify(myWorkspace),
  });
});


Solution

axios.get executes asynchronously. Which means the res.render method will probably execute before getting the response from API. That's why you got an empty array.

Change to this:

axios.get(...).then(function(response) {
  myWorkspace.push(response.data["workspaces"]);
  res.render('fullscreen', {
    workspace: JSON.stringfy(myWorkspace)
  })
})

See below demo:

// simulate axios.get to make a HTTP call
function get() {
  return new Promise((resolve) =>
    setTimeout(() => {
      resolve([1, 2, 3]);
    }, 1000),
  );
}

(function controller() {
  var myWorkspace = [];
  get().then((res) => {
    myWorkspace = res;
    console.log('get response:', myWorkspace);
  });
  // res.render will print firstly
  console.log('res.render:', myWorkspace);
})();

The execution result:

res.render: []
get response: [ 1, 2, 3 ]


Answered By - slideshowp2
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.