当axios发送POST请求CORS时,$ _ POST为空 [英] $_POST is empty when axios send POST request CORS

查看:470
本文介绍了当axios发送POST请求CORS时,$ _ POST为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在React app中将带有json数据的POST请求发送到PHP服务器时,$ _POST为空. 而且php://input也不起作用.

When I send POST request with json data in React app to PHP server, $_POST is empty. And also php://input doesn't work.

我尝试使用以下代码.

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 server is running on CloudFlare. I wonder if this is related with Cloudflare's cache process or not.

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

I hope any helps, Thank you in advance.

推荐答案

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

while sending from axios you need to change headers

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

这篇关于当axios发送POST请求CORS时,$ _ POST为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆