3
votes

I use axios to communicate with my own API (not written in NodeJS).

When I post a non simple request axios always goes directly to the catch block displaying a network error in the console, even with 2 successful Http Requests.

Headers requests

Error: Network Error Stack trace: createError@http://localhost:3000/static/js/bundle.js:1634:15 handleError@http://localhost:3000/static/js/bundle.js:1170:14


There is also a CORS warning about a missing header

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

However it is included in the Options Request!

options

When I add 'Access-Control-Allow-Origin': '*' in the Axios request headers, the warning is gone, but the browser doesn't fire a Post request after the successful Options request.

For the sake of being complete here are the post request headers.

post


The code:

postForm = () => {
    axios.post("http://127.0.0.1:8080/",
            myComplexObj, {
                headers: {
                    //'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json'
                },
                timeout: 15000
            }
        ).then(res => {
            console.log(res);
            alert('success');
        })

        .catch(function(error) {
            //code always end up here
            console.log(error);
            /*Error: Network Error
           Stack trace:
           createError@http://localhost:3000/static/js/bundle.js:1634:15
           handleError@http://localhost:3000/static/js/bundle.js:1170:14
           */

            console.log(error.response);      //undefined
            console.log(error.response.data); //undefined
            }
        })

Any help is gladly appreciated. What I have tried:

  • Remove the timeout //no change
  • Remove the Catch block //still no success
  • Return status code 204 on Options and/or Post requests //no difference
1

1 Answers

1
votes

You are confusing because status 200, however, the browser will not allow you to access the response of a CORS request if the Access-Control-Allow-Origin header is missing.

Here are some great articles that explain how CORS works:

https://www.html5rocks.com/en/tutorials/cors/
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Anyway, I think that you are using Django. So, you need add to settings.py:

CORS_ORIGIN_WHITELIST = (
   'localhost:8080',
   'localhost'
)

Or wherever you have the axios code.