0

I am practicing fetching data from APIs and with Fetch in Reactjs and on Codesandbox.io

The problem that sometimes I get the data and sometimes not. Here is a working example, it prints data to my console

componentDidMount() {
  fetch("https://www.reddit.com/r/redditdev/top.json")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => console.error(error));
}

For this url it works (also with https://api.github.com/orgs/nodejs), but if I change the url to "https://www.cryptocompare.com/api/data/coinlist/" or "https://chasing-coins.com/api/v1/std/coin/BTC" it doesn't work.

tarek hassan
  • 772
  • 11
  • 35
  • If you take a look at the response headers sent by the APIs, you will notice that the ones which work have the 'access-control-allow-origin: *' header set. The other ones are missing those headers, which makes your browser prevent the cross-origin request for security reasons (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) In case you're using your own server component, you could fetch the data on the server side (and depending on the server's origin, add the allow origin header as above). – Jan Wendland Aug 27 '18 at 15:38
  • 1
    Possible duplicate of [Understanding AJAX CORS and security considerations](https://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) – zero298 Aug 27 '18 at 16:30

0 Answers0