简体   繁体   中英

Cant access get results from fetch api request

I've been trying to access the array results from my fetch api request. I can get the results to return and parse it from json into a javascript object. However I cant access the results. The array is that is return called results. I wondering what I'm missing. The ultimate aim of the project is to get 12 random profiles from the api and get it to display to the card div. The error message I'm getting is 'Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at app.js:40'

HTML

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Public API Requests</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link href="css/normalize.css" rel="stylesheet">
        <link href="css/styles.css" rel="stylesheet">
    </head>
    <body>


        <header>
            <div class="header-inner-container">
                <div class="header-text-container">
                    <h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
                </div>

                <div class="search-container">

                </div>
            </div>
        </header>

        <div id="gallery" class="gallery">

        </div>


    </body>
    <script type="text/javascript" src="app.js"></script>
</html>

Javascript


const gallery = document.getElementById('gallery');
const card = document.createElement('div');
card.classList.add('card');
gallery.appendChild(card);

function fetchData(url) {
    return fetch(url)
            .then(response => { return response.json()})
            .then(data => {console.log(data)})
            .catch(error => {console.log('Error with fetching API', error)})
          }

function generateInfo(data) {

   const info = data.map( item => `
    <div class="card-img-container">
        <img class="card-img" src="${data}" alt="profile picture">
    </div>
    <div class="card-info-container">
        <h3 id="name" class="card-name cap">${name.first} ${name.last}</h3>
        <p class="card-text">${data.email}</p>
        <p class="card-text cap">${location.city}</p>
    </div>
    `)

    card.innerHTML = info;
  }

fetchData('https://randomuser.me/api/')
  .then(data => generateInfo(data.results));

The error is clear, the object you are getting in data is not defined, that's why it does not have a result key.

Check that data is coming from the URL. When I fetch the URL there is JSON coming in.

Also note that in the second then you have for debugging is not returning the data variable, and that's why you get nothing afterwards.

Add a return statement like: return data;

Extra info related to the catch part from docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API if you want to check for errors look at the status code from response.

The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

Change the fetchData function, remove .then block where you are getting final data, attach it when calling fetchData

function fetchData(url) {
    return fetch(url)
            .then(response => { return response.json()})
            .catch(error => {console.log('Error with fetching API',               
error)})}




fetchData('https://randomuser.me/api/')
   .then(data =>generateInfo(data.results)); //success to the final promise

Now inside generate info use foreach() instead of map().Since for each user object you need to create card.

function generateInfo(results) {
   results.forEach( userObj =>{
    const card = document.createElement('div');
    card.classList.add('card');
    card.innerHTML = `
    <div class="card-img-container">
        <img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture">
    </div>
    <div class="card-info-container">
        <h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3>
        <p class="card-text">${userObj.email}</p>
        <p class="card-text cap">${userObj.location.city}</p>
    </div>
    `;
    gallery.appendChild(card);
    })
 }

Run the following snippet to check if it works.

 const gallery = document.getElementById('gallery'); function fetchData(url) { return fetch(url) .then(response => { return response.json()}) .catch(error => {console.log('Error with fetching API', error)})} function generateInfo(results) { results.forEach( userObj =>{ const card = document.createElement('div'); card.classList.add('card'); card.innerHTML = ` <div class="card-img-container"> <img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture"> </div> <div class="card-info-container"> <h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3> <p class="card-text">${userObj.email}</p> <p class="card-text cap">${userObj.location.city}</p> </div> `; gallery.appendChild(card); }) } fetchData('https://randomuser.me/api/') .then(data =>generateInfo(data.results));
 <header> <div class="header-inner-container"> <div class="header-text-container"> <h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1> </div> <div class="search-container"> </div> </div> </header> <div id="gallery" class="gallery"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM