Axios: getting two requests OPTIONS & POST

こ雲淡風輕ζ 提交于 2021-01-21 06:24:29

问题


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:

OPTIONS:

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);
            })
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/48255545/axios-getting-two-requests-options-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!