[英]Unable to send POST data using fetch: React
I'm trying to send POST data to the PHP script on a different origin
using javascript fetch API in react. 我试图使用javascript fetch API在响应中将POST数据发送到不同
origin
的PHP脚本。 I've got a CORS policy error as can be seen below: 我有一个CORS政策错误,如下所示:
In order to solve the above problem, i added these two lines to my PHP script: 为了解决上述问题,我在PHP脚本中添加了以下两行:
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
But i'm still unable to get my problem solved. 但是我仍然无法解决我的问题。 The POST data is not being sent.
POST数据未发送。
JS code: JS代码:
fetch('http://localhost/articles-mania/publish.php', {
method: 'POST',
body: data, // JSON Object
headers : {
'Content-Type': 'application/json'
}
})
.then((res) => res.json())
.then((response) => {
this.setState({
responseMsg: response.msg
})
})
PHP Script: PHP脚本:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
$title = $_POST['article_title'];
echo json_encode(array('msg' => $title));
Any idea? 任何想法?
Perhaps try allowing the OPTIONS
method as that is used to perform the pre-flight request... 也许尝试允许使用
OPTIONS
方法来执行飞行前请求...
Change this: 更改此:
header('Access-Control-Allow-Methods: GET, POST, PUT');
To This: 为此:
header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');
I just came across a similar issue where it seemed like I had all my CORS settings properly in place. 我刚遇到一个类似的问题,似乎我所有的CORS设置都正确到位。 What worked for me was adding a JSON.stringify() to the object you're passing into the body parameter.
对我有用的是在要传递给body参数的对象中添加一个JSON.stringify()。
Eg 例如
fetch('http://localhost/articles-mania/publish.php', {
method: 'POST',
body: JSON.stringify(data), // JSON Object
headers : {
'Content-Type': 'application/json'
}
})
.then((res) => res.json())
.then((response) => {
this.setState({
responseMsg: response.msg
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.