You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fetch发送POST请求到PHP后端返回null,错误出在哪里?

问题原因

  • 你调用fetch传递JSON格式请求体时,没有主动设置Content-Type: application/json请求头,PHP的$_POST超全局数组仅支持解析application/x-www-form-urlencoded、multipart/form-data两种格式的请求数据,无法自动解析JSON格式的请求体,因此$_POST['test']读取为空,json_encode处理空值就会返回null。
  • 直接读取$_POST['test']未做判空处理时,PHP会抛出Notice级别的错误信息,也可能破坏返回结果的JSON格式。

修复方案

方案1:前后端适配JSON交互(推荐,符合前后端分离开发规范)

  1. 前端fetch请求添加Content-Type请求头配置:
fetch('http://localhost/test.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        test: 'test'
    })
})
     .then(res => res.json())
     .then(data => console.log(data))
  1. PHP后端改为从原生输入流读取JSON请求数据:
<?php
// 读取原始请求体内容
$rawInput = file_get_contents('php://input');
$params = json_decode($rawInput, true);
// 判空避免变量不存在时报错
$testValue = $params['test'] ?? '';
echo json_encode($testValue);

方案2:前端适配PHP默认表单解析逻辑,后端无需修改

前端将请求体改为FormData格式,fetch会自动设置匹配的Content-Type,PHP的$_POST可以直接解析:

const formData = new FormData();
formData.append('test', 'test');

fetch('http://localhost/test.php', {
    method: 'POST',
    body: formData
})
     .then(res => res.json())
     .then(data => console.log(data))

小提示:PHP输出JSON响应时建议使用echo代替print_r,避免特殊场景下输出额外调试信息破坏JSON格式。

内容的提问来源于stack exchange,提问作者KaKi786

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:57:02