Vue-axios POST 非表单数据在 PHP 中无法获取的解决方案
问题描述
当使用 vue-axios 向服务器后端发起 POST 请求提交数据时,经常遇到 PHP 服务端无法正确接收或解析 POST 数据的情况。
问题解决
修改 php.ini 配置
首先检查并编辑 php.ini 配置文件,定位到 enable_post_data_reading 变量,将其值设置为 On 以启用状态,并确保该行未被分号注释掉。
; Whether PHP will read the POST data.
; This option is enabled by default.
; Most likely, you won't want to disable this option globally. It causes $_POST
; and $_FILES to always be empty; the only way you will be able to read the
; POST data will be through the php://input stream wrapper. This can be useful
; to proxy requests or to process the POST data in a memory efficient fashion.
; http://php.net/enable-post-data-reading
enable_post_data_reading = On //大约656行,修改此条
然而,仅修改上述配置后,问题可能依然存在,此时需要进一步查阅相关资料寻找其他原因。
获取非表单数据
经过资料搜集发现,vue-axios 默认向后端发送的是非表单格式的数据(与传统的 Ajax 不同)。对于此类非表单数据,PHP 需要通过 php://input 流来获取原始请求内容。
$raw = file_get_contents('php://input');//获取非表单数据
echo $raw;//输出结果
注意:在前端发送 POST 请求时,必须将请求头 Content-type 设置为 application/json; charset=utf-8
headers: {
"Content-type": "application/json; charset=utf-8"
}