[英]Unable to send POST data using fetch: React
我試圖使用javascript fetch API在響應中將POST數據發送到不同origin
的PHP腳本。 我有一個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');
我剛遇到一個類似的問題,似乎我所有的CORS設置都正確到位。 對我有用的是在要傳遞給body參數的對象中添加一個JSON.stringify()。
例如
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.