Access Control Origin Header error using Axios in

2019-04-04 19:34发布

问题:

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

回答1:

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

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

If not - you must ensure the server can manage the CORS-requests.

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



回答2:

As I understand the problem is that request is sent from localhost:3000 to localhost:8080 and browser rejects such requests as CORS. So solution was to create proxy

My solution was :

import proxy from 'http-proxy-middleware'
app.use('/api/**', proxy({ target: "http://localhost:8080" }));


回答3:

Using the Access-Control-Allow-Origin header to the request won't help you in that case while this header can only be used on the response...

To make it work you should probably add this header to your response.You can also try to add the header crossorigin:true to your request.