Accessing an item from a web API is returning undefined

Viewed 33

I am trying to learn how to use web APIs and am trying a little exercise where i use axios to access an api that returns quotes from famous people (bit arbitrary but its just for learning sake). I have connected to the API fine and I can get an object back that has the quote data in it as below:

const axios = require("axios");
const options = {
  method: 'GET',
  url: 'https://famous-quotes4.p.rapidapi.com/random',
  params: {category: 'technology', count: '1'},
  headers: {
    'X-RapidAPI-Key': 'secret key',
    'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com'
  }
};

axios.request(options).then(function (response) {
  let quote = response.data; 
    console.log(quote);
}).catch(function (error) {
    console.error(error);
});

It returns to the console as below:

 {
    id: 67538,
    author: 'Stewart Brand',
    text: "Once a new technology rolls over you, if you're not part of the steamroller, you're part of the road.",
    category: 'technology'
  }

However the problem comes where i want to refine it further and just console log the quote rather than the whole object. I tried the below:

axios.request(options).then(function (response) {
  let quote = response.data;
    console.log(quote.text);
}).catch(function (error) {
    console.error(error);
});

But that gives me an "undefined" result.

Can anyone advise me on the best way to extract just that one item from the object?

1 Answers

OK it turns out Amit Kumar is correct - I changed the code to console.log(quote[0].text); and it worked just fine.

the console.log(typeof quote) returning an object must be a red herring

Thanks for the help!

Related