Axios: getting two requests OPTIONS & POST

Shrroy picture Shrroy · Jan 15, 2018 · Viewed 25k times · Source

I have a React app built using Redux and React and I'm trying to post data. Everything works fine, but I don't know why I'm getting two requests OPTIONS & POST

Perhaps because the API URL isn't on the same server as react.

POST: enter image description here

OPTIONS: enter image description here

Here's the code:

const url = 'http://rest.learncode.academy/api/johnbob/myusers';

export function postUsers(username, password) {
    let users = {
        username,
        password,
    };
    return{
        type: "USERS_POST",
        payload: axios({
            method:'post',
            url:url,
            data: users,
        })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            })
    }
}

Answer

Yangshun Tay picture Yangshun Tay · Jan 15, 2018

Non-simple CORS requests via AJAX are pre-flighted. Read more about it here. This is a browser behavior and nothing specific to axios. There's nothing inherently wrong with this behavior and if it's working for you, you can just leave it.

If you insist on getting rid of it, there are a few ways you can go about:

  1. You can set Access-Control-Allow-Origin: * on your server to disable CORS.

  2. Make your CORS request a simple one. You will have to change the Content-Type header to application/x-www-form-urlencoded or multipart/form-data or text/plain. No application/json.

I'd say just leave it as it is if the OPTIONS request is not blocking you.