Home > Blockchain >  Fetching Rapid API data
Fetching Rapid API data

Time:12-12

[Data Screenshot][1] Hi, I am trying to fetch information from quote API (Quote, Author), but I am having difficulty to fetch author data. Could you please help on this?

(especially for below code line

  .then(response=> {document.getElementById("quoteauthor").innerHTML=response.originator[1]})

)

Below is JS file

const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': 'Key',
        'X-RapidAPI-Host': 'quotes15.p.rapidapi.com'
    }
};
function getQuote(){
fetch('https://quotes15.p.rapidapi.com/quotes/random/', options)
    .then(response => response.json())
       .then(response=> {document.getElementById("quote").innerHTML=response.content})
       .then(response=> {document.getElementById("quoteauthor").innerHTML=response.originator[1]})
    .catch(err => console.error(err));}

below is HTML file body section

<body>
    <button onclick="getQuote()">Give me a quote!</button>

    


 <div>
   
    <p style="text-align: center" id="quote"></p>;
    <p style="text-align: center" id="quoteauthor"></p>
 </div>

    <script src="script.js"></script>
</body>
[Not displaying author][2]


  [1]: https://i.stack.imgur.com/XD17C.jpg
  [2]: https://i.stack.imgur.com/mejNQ.jpg

CodePudding user response:

I think that the problem is that you tried

response.originator[1]

response.originator is not an array, is a map, so you should do for the author's name

response.originator.name

and for the quote itself

response.content

CodePudding user response:

You didn't get a "quoteauthor" because of an error: "TypeError: response is undefined".

You can try to debug your code in order to figure out where fetch is failing (maybe it's because of catch part), also use console.log() it will help you in your investigations.

Let me a little bit rewrite your code snippets if you don't mind.

HTML part

<body>
<button id="getQuote">Give me a quote!</button>
<div>
  <p style="text-align: center" id="quote"></p>
  <p style="text-align: center" id="quoteAuthor"></p>
 </div>
<script src="script.js"></script>
</body>

JavaScript part

const quoteButton = document.getElementById('getQuote');
const quote = document.getElementById('quote');
const quoteAuthor = document.getElementById('quoteAuthor');

const options = {
  method: 'GET',
  headers: {
    'X-RapidAPI-Key' : 'your_key',
    'X-RapidAPI-Host': 'quotes15.p.rapidapi.com'
  }
};

quoteButton.addEventListener('click', getQuote);

async function getQuote() {
  try {
    const response = await fetch('https://quotes15.p.rapidapi.com/quotes/random/', options);

    if (!response.ok) {
        throw new Error(`Getting error: ${response}`);
    }

    const data = await response.json();
    quote.innerHTML = data.content;
    quoteAuthor.innerHTML = data.originator.name;
  } catch (error) {
      console.log(error);
  }
}

With this approach you've got a quote and an author

  • Related