Access Control Origin Header error using Axios in React Web throwing error in Chrome

SeaWarrior404 picture SeaWarrior404 · Aug 31, 2017 · Viewed 129.6k times · Source

Im making an API call using Axios in a React Web app. However Im getting the error in Chrome as,

XMLHttpRequest cannot load https://example.restdb.io/rest/mock-data. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

    {
      axios.get('https://example.restdb.io/rest/mock-data', {
      headers: { 
      'x-apikey': 'API_KEY',
      },
    responseType: 'json',
     }).then(response => {
      this.setState({ tableData: response.data });
    });
    }

I have also read several answers on StackOverflow about the same issue, titled "Access-Control-Allow-Origin" but still coudnt figure out how to solve this. I dont want to use an extension IN Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.

After trying out few answers I have tried with this,

    headers: { 
      'x-apikey': '59a7ad19f5a9fa0808f11931',
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
    },

Now I get the error as,

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

Answer

Vlad Povalii picture Vlad Povalii · Aug 31, 2017

If your backend support CORS, you probably need to add to your request this header:

headers: {"Access-Control-Allow-Origin": "*"}

[Update] Access-Control-Allow-Origin is a response header - so in order to enable CORS - you need to add this header to the response from your server.

But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS.

You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS