Java script fetch returns 200 but no data

Viewed 3860

I have a requirement to display all the countries in the world in a drop down. So I found this api end point END POINT LINK. When I copy and paste this end point link in my web browser I got a response with all the data. (countries);

When I try to embed this in project.

getCountries() {
      try {
       
        fetch(`https://restcountries.eu/rest/v1/all`).then(data =>
          console.log(data)
        );
        
      } catch (error) {
        console.log("HERE ERROR COMES", error);
      }
    }

It does go to then block of the fetch method. But gives me the output enter image description here

There is nothing called data here. Even I get a success respond. Why could this happen? Is this something related to cors errors?

3 Answers

You can use as follow:

let url = 'https://restcountries.eu/rest/v1/all';

fetch(url)
.then(res => res.json())
.then((data) => {
  console.log(data);
})
.catch(err => { throw err });

This works for me

function getCountries(){
  fetch("https://api.printful.com/countries ")
  .then((resp) => resp.json()) // Transform the data into json
  .then(function(data) {
     let countries = data.result;
     return countries.map(function(country){
        console.log(country.name);
        //Create your list here
     });
    });
}

responce.type 'cors' probably means Cross Origin Request - and it's blocking it - try to find another api

Related