1

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

2 Answers 2

1

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.

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

Comments

0

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()).

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.