PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

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

 October 14, 2022     axios, express, node.js     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing