35

I'm trying to post data. Everything works fine, but I don't know why I'm getting two requests OPTIONS & POST

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);
            })
    }
}
Liam
  • 6,517
  • 7
  • 25
  • 47

1 Answers1

53

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, multipart/form-data, or text/plain. Not application/json.

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

Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141