Home > Net >  Issues displaying data in node js , ejs
Issues displaying data in node js , ejs

Time:11-15

I am a newbie i have been trying to fetch data from an API using node js express and ejs. My problem is that i cannot display the data in my page. looks like something is wrong with the way that i render the data . when i console.log my response, i have access to it but it does not seem to want to display can you help me plz.

I tried to fetch the data like this :

const fetch = require('node-fetch');
  exports.allCarte = async (req, res) => {
 
fetch('https://pokeapi-enoki.netlify.app/')
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.json();
   
  })
  .then((response) => {
    console.log(response)
   res.render("../views/home",{
    response
   })
  });

}

and here is what I did in the home.ejs :

<body>
        <main>
         
          <ul>
            <% for(var i = 0; i < response.length; i  ) {%>
             
              <li><%=response[i].name %></li>
              
             
            <% } %>
            <h1>Hi, there!</h1>
          
      
           
          </ul>
        </main>
 
    
<

CodePudding user response:

If you have a look at results from the https://pokeapi-enoki.netlify.app/ API, it is structured something like this:

{
  "pokemons": [
    {
      "id": 1,
      "name": "germignon",
       ...    
    },
    {
      "id": 2,
      "name": "kaiminus",
      ...

...which means the array of interest is response.pokemons not just response.

Your home.ejs should be changed like this:

  <% for(var i = 0; i < response.pokemons.length; i  ) {%>
    <li><%=response.pokemons[i].name %></li>
  <% } %>
  • Related