javascript Axios:获取两个请求 OPTIONS 和 POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48255545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:54:43  来源:igfitidea点击:

Axios: getting two requests OPTIONS & POST

javascriptreactjsreduxreact-reduxaxios

提问by Shrroy

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

我有一个使用 Redux 和 React 构建的 React 应用程序,我正在尝试发布数据。一切正常,但我不知道为什么我收到两个请求OPTIONS&POST

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

也许是因为 API URL 与 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);
            })
    }
}

回答by Yangshun Tay

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.

通过 AJAX 的非简单 CORS 请求是预检的。在此处阅读更多相关信息。这是浏览器行为,与 axios 无关。这种行为本身没有任何问题,如果它对你有用,你可以放弃它。

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-Typeheader to application/x-www-form-urlencodedor multipart/form-dataor text/plain. No application/json.

  1. 您可以Access-Control-Allow-Origin: *在服务器上设置禁用 CORS。

  2. 使您的 CORS 请求变得简单。您必须将Content-Type标题更改为application/x-www-form-urlencodedormultipart/form-datatext/plain。没有application/json

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

如果OPTIONS请求没有阻止您,我会说就保持原样。