4

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?

4
  • 4
    What's in body? Commented Sep 13, 2018 at 11:45
  • Have you looked at response.body? Have you tried response.json() ?Does the response have the correct data type? Read the specifications of the fetch API to find which response method is appropriate for whatever the restcountries server returned you. What you call data is a Response object. You have to handle that response according to what you are fetching and create the real data object yourself. Commented Sep 13, 2018 at 11:47
  • also, this try...catch won't do the job ;) Commented Sep 13, 2018 at 11:51
  • I think the problem was unlike axios you can't directly access response data in the fetch method. You have to convert it into json and then access it. I marked answer and it worked for me. =) Thank you guys all. Commented Sep 14, 2018 at 3:10

3 Answers 3

6

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 });

Sign up to request clarification or add additional context in comments.

2 Comments

is it necessary to throw in catch ? It will be wrapped into Promise.reject(err)
Oh, I don't know about it. This my code is basic using ...
1

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
     });
    });
}

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.