miouri
miouri

Reputation: 409

API fetch is not responding

I was working on a React APP which fetches data from https://restcountries.com/v2/all and now I have an error.

useEffect(() => {
  fetch(`https://restcountries.com/v2/all`)
    .then((r) => r.json())
    .then((data) => {
      if (data !== undefined) {
        setCountries(data);
      } else {
        alert('Can´t Load Data');
      }
    });
}, []);

enter image description here

Upvotes: 2

Views: 1914

Answers (3)

AmirYousaf
AmirYousaf

Reputation: 21

this is happening due to multiple reason like due to authentication or your are not sending token in request header second due to server down or may be your are passing wrong param to request third one my be this endpoint can me access by only specific domains url.

Upvotes: 0

Prince Hamza
Prince Hamza

Reputation: 1748

You are getting a CORS error which means target domain of api (restcountries) does not allow other domains to fetch data. The solution to this problem is a server side browser or headless browser. Like selenium and puppeteer

https://www.selenium.dev/

https://github.com/puppeteer

But i have tested and api is giving me data in browser with same fetch code. I cant reproduce the problem. Its an issue with something else

Upvotes: 0

AmirYousaf
AmirYousaf

Reputation: 21

**

use this format with header

** ##

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {`enter code here`
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}
}, []);

Upvotes: 1

Related Questions