Java script fetch returns 200 but no data

断了今生、忘了曾经 提交于 2019-12-24 11:37:44

问题


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

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


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/52312991/java-script-fetch-returns-200-but-no-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!