Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/45975135/access-control-origin-header-error-using-axios-in-react-web-throwing-error-in-ch

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...