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

当我在React app中将带有json数据的POST请求发送到PHP服务器时,$ _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的缓存过程有关。

希望对您有所帮助,谢谢。

xuekequn230 回答:当axios发送POST请求CORS时,$ _ POST为空

使用以下标题

它在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': '*'
}
本文链接:https://www.f2er.com/3166508.html

大家都在问