Axios GET Request Response is Undefined

Asked

Viewed 1,299 times

1

I’m trying to make an Next call in my Node JS Express app and sending the data to my index.ejs file. The problem is that i can see the data in my callApijavascript file but i cant access the Response in my app.js (Undefined value).

This is the Relevant code from my app js. file:

 //iNDEX pAGE RENDER
app.get('/', function (req, rep) {
    var response = callApi.GetAll();
    var users = response.users;
    var activities = response.activities;
    console.log('Users ' + users);
    console.log('Activities ' + activities);
    rep.render('index', {
        users: users,
        activities: activities
    });
});

Here’s my callApi.js the logs here Return the api data Perfectly

var GetAll = function () {
  axios.all([
      axios.get(initGet.uri + 'users/'),
      axios.get(initGet.uri + 'activities/')
    ])
    .then(axios.spread(function (userResponse, activitiesResponse) {
      console.log('User', userResponse.data);
      console.log('Activities', activitiesResponse.data);
      return {
        users: userResponse.data,
        activities: activitiesResponse.data
      };

    }));

};
module.exports = {
  GetAll: GetAll
};

My Error when i run index.ejs {"error":{"message":"Cannot read Property 'users' of Undefined"}}

Thanks in Advance.

  • 2

    Please translate your question, this is Stackoverflow in English

1 answer

3


If GetAll is a function she needs to have a return. At this point the function does not return anything... when it should return a Promise.

Adds a return here:

var GetAll = function () {
  return axios.all([

Note also that to consume the result of a Promise you have to use the then. So the rest of the code has to be inside a then. That is to say:

callApi.GetAll().then(response => {
    var users = response.users;
    // o resto do código aqui...
});

Two suggestions:

  • uses big letters only for builders. When I see GetAll I think the intention is to use new GetAll();, which is not the case.
  • uses const and let whenever possible. Leaves the "little old lady" var go down in history.
  • 1

    Thank you so much now it works! !

  • @Afonsomartinho ótimo! If you want you can click to mark the answer as accepted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.