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.
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);
})
}
}
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:
You can set Access-Control-Allow-Origin: *
on your server to disable CORS.
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.