CORS error while making axios.get call

2020-02-26 19:49发布

问题:

I'm using axios to make a axios.get call in my redux action.js file. In my component this action is performed on form submission.

I'm getting status 200 in my console but not getting any response back. I'm getting the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:\\\\localhost:3000' is therefore not allowed access.

Has anybody came across such error too? Would you please share on how to resolve this.

回答1:

The problem is not with axios. The issue is with the server. When you serve up data you must add the following headers, before sending it.

Access-Control-Allow-Origin must be set to *

Access-Control-Allow-Headers must be set to Origin, X-Requested-With, Content-Type, Accept



回答2:

The first confusion I had tackling this problem was understanding what a preflight request means. So I will start from there.

Browsers send preflight requests whenever a request does not meet these criteria:

  1. HTTP methods matches one of (case-sensitive):
    • GET
    • POST
    • HEAD
  2. HTTP Headers matches (case-insensitive):
    • Accept
    • Accept Language
    • Content Language
    • Last-Event-ID
    • Content-Type, but only if the value is one of:
      • application/x-www-form-urlencoded
      • multipart/form-data
      • text/plain

Preflight requests are made with an OPTIONS method that includes three additional headers that your server may not be expecting if it is not configured for CORS. They are:

  • Access-Control-Allow-Headers
  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods

If the server isn't configured for CORS, it simply responds with an empty header having HTTP status code 200. Once you have configured the server for CORS, you should include the headers listed above as headers supported by CORS.

That should clear the error and allow you communicate with the server.

Note: While your server can handle the custom header you created (in my case, Authorization for JWT authentication), it most likely won't be configured for CORS request. If you have access to your server, simply find out how to configure CORS for that server.

For more information about CORS. See https://www.html5rocks.com/en/tutorials/cors/



回答3:

This worked for me:

axios.create({
    baseURL: "http://localhost:8088"
  }).get('/myapp/user/list')
    .then(function(response) {
      callback && callback(response);
      debugger;
    })