简体   繁体   中英

how to proceed further with this API

To brush up on my web development skills I am trying to re-learn API. I got the from this website: https://documenter.getpostman.com/view/10808728/SzS8rjbc?version=latest

In my JS file, I have the following code:

var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

fetch("https://api.covid19api.com/summary", requestOptions)

  .then(response => response.text())

  .then(result => console.log(result))

  .catch(error => console.log('error', error));

And I see that it logs a lot of data, but I'm not sure how to grab a specific data from the API and display it on the HTML page.

I tried something like this in the JS file:

var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

fetch("https://api.covid19api.com/summary", requestOptions)

  .then(response => response.text())

  .then(result => console.log(result))

  .catch(error => console.log('error', error));

let tdeaths = data.global.TotalDeaths;

document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');

But nothing is showing up on my HTML file with

you have to put your code in the .then statement. So it should look like this:

fetch("https://api.covid19api.com/summary", requestOptions)

  .then(response => response.json())

  .then(result => {
   let tdeaths = result.global.TotalDeaths;
   document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');
   })

  .catch(error => console.log('error', error));

I see there are two problems.
1. How are you updating data.global.TotalDeaths ? it will take the initial value because tdeaths is not getting output from response.
2. The document.getElementByid statement would run before it retrives values from API. so after fixing 1st issue, you should put the statement like below(considering result = data)

.then(result => {
     let tdeaths = result.global.TotalDeaths;
     document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');
  })

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