thinkphp 6.0 中 input() 或 $request->param() 接收 json 数据返回空数组,是因为框架默认不解析原始 json 请求体,需手动读取 php://input 并 json_decode;须确认 content-type 为 application/json、请求体为纯 json 字符串,并在调用任何 request 方法前一次性读取流。

ThinkPHP 6.0 中通过 input() 或 $request->param() 接收前端 POST 的 JSON 数据时返回空数组,是因为框架默认不解析原始 JSON 请求体,必须手动读取 php://input 流并解码才能拿到真实数据。
确认请求头与数据格式是否正确
第一步:检查前端是否设置了 Content-Type: application/json。若未设置,TP6 会跳过 JSON 解析逻辑,直接按表单格式解析空内容。
第二步:用浏览器开发者工具或 Postman 查看 Network → Payload,确认发送的是纯 JSON 字符串(如 {"name":"张三","age":25}),而非键值对 FormData 或 URL 编码格式。
第三步:在控制器开头加一行调试代码:var_dump(file_get_contents('php://input'));。如果输出为空字符串,说明请求体根本没传过来——可能是前端未调用 JSON.stringify(),或 Axios/Fetch 忘了设 body。
使用 php://input 手动读取并解析
方法一:在控制器中直接读取
在需要接收 JSON 的方法里,第一行写:$raw = file_get_contents('php://input');。这一步必须放在任何 $this->request->xxx() 调用之前,因为 php://input 只能读取一次,后续再读返回空。
接着执行:$data = json_decode($raw, true);。如果 $data === null,说明 JSON 格式非法,可用 json_last_error_msg() 查错。
方法二:封装成公共方法复用
在 BaseController 中添加 protected function getJsonInput() { $raw = file_get_contents('php://input'); return json_decode($raw, true) ?: []; }。这样子类控制器直接调用 $this->getJsonInput() 就能拿到关联数组。
配置中间件自动解析 JSON 请求
第一步:创建中间件 app/middleware/JsonInput.php
第二步:在 handle 方法中写:if ($request->contentType() === 'application/json') { $raw = file_get_contents('php://input'); $data = json_decode($raw, true); if (json_last_error() === JSON_ERROR_NONE) { <strong>【$request->merge($data);】</strong> } }
第三步:在 app/middleware.php 中全局注册该中间件,或在路由定义时单独绑定:Route::post('api/user', 'User/save')->middleware('json_input');
注意:调用 $request->merge() 后,后续所有 $request->param()、$request->post() 都能直接取到 JSON 字段,但原始 php://input 已被消耗,不能再重复读取。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











