Home > Enterprise >  I can't access data from api in node js
I can't access data from api in node js

Time:09-28

I'm trying to obtain data from an API with Axios and then pass it into an EJS template, but I'm not sure where the problem is!

Here is the code:

router.get("/", async (req, res, next) =>  
   
    try {
       const apiData = await axios.get("http://localhost:8080/api/v1/users/?key=API_KEY");         
       res.render('pages/home',{
           apiData: JSON.stringify(apiData),
       });
    }
    catch (err){
       console.log(err)
    }
});

EJS Template:

<% apiData.forEach(user => { %>
 <?= user.data.firstname ?> <br>
<% }) %>

NB. The API data from the URL are structured this way:

{
    "success": true,
    "total": 3,
    "data": [
        {
        "reference": "",     
        "firstname": "firstname",
        "lastname": "lastname",
        "email": "[email protected]",
        "mobile": "(011) 111-111",
        "avatar": "avatar.jpg",
        "is_active": 0,
        "is_verified": 0,
        "created_at": "2022-09-16T11:41:19.000Z",
        "validated_at": null
        },
        {
            .... 
        }
    ]
}

Important: Im new to node js, so forgive me if I'm mixing things up

CodePudding user response:

Make three changes.

First, use await with your axios call.

Then, second don't use JSON.stringify() when passing data to your template. Pass an actual Javascript object.

router.get("/", async (req, res, next) =>  
   
    try {
       const response = await axios.get("http://localhost:8080/api/v1/users/?key=API_KEY");         
       res.render('pages/home', {apiData: response.data});
    }
    catch (err){
       console.log(err)
       // send error response
       res.sendStatus(500);
    }
});

Then, third, use apiData.data.forEach() in your template because it's the data property that is the array, not the top level object.

CodePudding user response:

axios.get is an async method, you should use await

const apiData = await axios.get("http://localhost:8080/api/v1/users/?key=API_KEY");         
  • Related