Developer Here
Developer Here

Reputation: 11

How to fetch data from api in react?

I want to fetch data from my API in react:

async componentDidMount(){
const url="https://covidensa.herokuapp.com/";
const response =await fetch(url);
const data=await response.json();
this.setState({ person:data.results,loading:false });
console.log(this.state.person)
console.log(this.state.option.option1.option2)
console.log(data.results)
}

I have this error:

Access to fetch at 'https://covidensa.herokuapp.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Area Chart.js:36 GET https://covidensa.herokuapp.com/ net::ERR_FAILED

Upvotes: 1

Views: 380

Answers (2)

Sanket Vyawahare
Sanket Vyawahare

Reputation: 130

Please use cors in your backend. If you are using Nodejs for server, do npm install cors and then import in your code and write app.use(cors()).

Upvotes: 0

Edward
Edward

Reputation: 435

The reason why you're not getting any data from your api is because CORS is blocking it. Cors stands for cross-origin resource sharing and it basically acts as security to block potentially malicious code such as scripts, etc...

The following is from the Mozilla documentation:

const response = await fetch(url, {
    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
  });

Notice how you only have

const response =await fetch(url);

You will need to add the parameters where mode is 'no-cors' as mentioned from your error message.

Upvotes: 1

Related Questions