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

Flutter调用Symfony 6 API登录接口返回500错误求助

问题根源

你的Symfony后端期望接收JSON格式的请求体,但Flutter前端发送的是application/x-www-form-urlencoded(表单编码)格式的数据,导致json_decode($request->getContent(), true)返回null,后续访问$data['mail']和$data['password']时触发" Trying to access array offset on value of type null"错误,最终返回500状态码。

解决方案

两种修复方式任选其一即可:

方式1:修改Flutter代码,发送JSON请求

将http.post的请求体改为JSON格式,并设置正确的Content-Type请求头:

final response = await http.post(
  url,
  headers: {'Content-Type': 'application/json'}, // 指定请求内容为JSON
  body: jsonEncode({ // 用jsonEncode序列化数据为JSON字符串
    'mail': mail,
    'password': password,
  }),
);

方式2:修改Symfony代码,兼容表单编码格式

如果需要后端同时支持JSON和表单编码请求,可调整参数获取逻辑:

#[Route('/login', name: 'login', methods: ['POST'])]
public function login(Request $request, UserRepository $userRepository, UserPasswordHasherInterface $passwordHasher): Response
{
    // 优先解析JSON,否则读取表单数据
    $data = json_decode($request->getContent(), true) ?? $request->request->all();
    
    // 校验必要参数是否存在
    if (!isset($data['mail'], $data['password'])) {
        return $this->json(['etat' => false, 'message' => '参数缺失'], Response::HTTP_BAD_REQUEST);
    }
    
    $mail = $data['mail'];
    $password = $data['password'];

    // 后续登录逻辑保持不变...
}
额外调试建议
  • 在Symfony控制器中临时添加日志,查看请求的内容和格式:
    error_log('Request content: ' . $request->getContent());
    error_log('Request content type: ' . $request->headers->get('Content-Type'));
    
  • Flutter端可打印请求的headers和body,确认发送的数据格式是否符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:59:57