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
Axios: getting two requests OPTIONS & POST
提问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 不在同一台服务器上。
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:
如果你坚持要摆脱它,有几种方法可以解决:
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-Typeheader toapplication/x-www-form-urlencodedormultipart/form-dataortext/plain. Noapplication/json.
您可以
Access-Control-Allow-Origin: *在服务器上设置禁用 CORS。使您的 CORS 请求变得简单。您必须将
Content-Type标题更改为application/x-www-form-urlencodedormultipart/form-data或text/plain。没有application/json。
I'd say just leave it as it is if the OPTIONSrequest is not blocking you.
如果OPTIONS请求没有阻止您,我会说就保持原样。


