简体   繁体   中英

Why am I getting undefined as an answer when fetching data from an api?

I learning how to use fetch api and I am trying to print a quote from the Simpsons api as practice. The problem is that keep getting undefined as an answer. Do you know why it is not just printing the quote?

let button    = document.querySelector('#button')
let quote      = document.querySelector('#quote')

function getInfoFetch(){

  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {

      quote.innerText = data.quote;

    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch)

The API's response appears to be an array, which means you'll need to need to access the quote data from say, the first item of the array response.

You can do that by making the following change to your code:

 let button = document.querySelector('#button') let quote = document.querySelector('#quote') function getInfoFetch(){ fetch('https://thesimpsonsquoteapi.glitch.me/quotes') .then(response => response.json()) .then((data) => { // Access first item of data "array" to retrieve and display quote quote.innerText = data[0].quote; }) .catch(err => console.log(err)); } button.addEventListener('click', getInfoFetch) 
 <button id="button">Get quote</button> <div id="quote"></div> 

Data which you are parsing is of Array type

[{"quote":"I can't even say the word 'titmouse' without gigggling like a schoolgirl.","character":"Homer Simpson","image":"https://cdn.glitch.com/3c3ffadc-3406-4440-bb95-d40ec8fcde72%2FHomerSimpson.png?1497567511939","characterDirection":"Right"}]

So to read that you need to pass index as well

fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {

      quote.innerText = data[0].quote;

    })
    .catch(err => console.log(err));

Here is working fiddle

The data of second .then is an array with a object inside. If you want to get quote in the object, you need to use data[0] to select the object.Then, use .quote to select the key quote in the object. And you can get the value you want.

let button = document.querySelector('#button');
let quote = document.querySelector('#quote');

function getInfoFetch(){
  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {
      console.log(data); 
      //this is an array with object(index = 0) inside [{...}]
      quote.innerText = data[0].quote;
    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch);

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