CORS error while making axios.get call

前端 未结 3 1587
春和景丽
春和景丽 2020-12-31 00:30

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

相关标签:
3条回答
  • 2020-12-31 01:08

    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/

    0 讨论(0)
  • 2020-12-31 01:13

    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

    0 讨论(0)
  • 2020-12-31 01:20

    This worked for me:

    axios.create({
        baseURL: "http://localhost:8088"
      }).get('/myapp/user/list')
        .then(function(response) {
          callback && callback(response);
          debugger;
        })
    
    0 讨论(0)
提交回复
热议问题