当axios发送POST请求CORS时,$_POST为空



当我在React应用程序中向PHP服务器发送带有json数据的POST请求时,$_POST为空。而且php://input不起作用。

我尝试使用以下代码。

PHP服务器端:

if($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization');
header('Access-Control-Max-Age: 1000');
header("Content-Length: 0");
header("Content-Type: text/plain");
} else if($_SERVER['REQUEST_METHOD'] == "POST") {
echo "Checking case1:n";
echo "<br/>";
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
echo "<br/>";
echo "Checking case2:n";
echo "<br/>";
var_dump($_POST);
}

反应侧代码:

axios.post(
'https://xx.xx.com/index2.php',
{
member: id
},
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
withCredentials: true
}
)

PHP服务器正在CloudFlare上运行。我想知道这是否与Cloudflare的缓存进程有关。

我希望有任何帮助,提前谢谢。

使用标题如下

它适用于我的PHP

headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
}

从axios发送时,您需要更改标题

headers: {
'Content-Type': 'multipart/form-data,multipart/form-data',
'Access-Control-Allow-Origin': '*'
}

最新更新