我正在尝试使用 javascript fetch API 将 POST 数据发送到不同 origin
上的 PHP 脚本在 react 。我有一个 CORS 策略错误,如下所示:
为了解决上述问题,我将这两行添加到我的 PHP 脚本中:
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
但我仍然无法解决我的问题。未发送 POST 数据。
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 脚本:
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));
有什么想法吗?
最佳答案
也许尝试允许 OPTIONS
方法,因为它用于执行飞行前请求...
改变这个:
header('Access-Control-Allow-Methods: GET, POST, PUT');
为此:
header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');
关于javascript - 无法使用 fetch : React 发送 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51263645/