thinkphp 8 默认使用 response 对象并遵循 psr-7 标准,导致直接返回数组或数据时格式与旧版自动包装不同。要统一接口返回格式,需要注册一个全局响应转换中间件,在输出前将原始数据(如数组、对象)统一序列化为包含状态码、消息和数据体的 json 结构。

如何配置全局中间件实现自动包装
通过创建自定义中间件并在 middleware.php 中注册,可以拦截所有 HTTP 响应。在中间件的 handle 方法中判断响应是否为 JSON 类型且内容尚未被序列化,若是则提取数据并重新构建符合业务规范的 JSON 字符串。

namespace app\middleware;
use think\Response;
use think\facade\Request;
class FormatResponse
{
public function handle($request, \Closure $next)
{
$response = $next($request);
// 仅处理 JSON 类型的响应
if ($response instanceof Response && $response->getType() === 'json') {
$data = $response->getData();
// 如果数据已经是数组或对象,进行统一包装
if (is_array($data) || is_object($data)) {
$result = [
'code' => 200,
'msg' => 'success',
'data' => $data
];
// 重新生成 JSON 响应
return json($result);
}
}
return $response;
}
}
在 app/middleware.php 中添加:'format_response' => \app\middleware\FormatResponse::class,。这样控制器只需返回 return ['id' => 1];,最终输出即为 {
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











