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

Flutter Web项目API请求遇FormatException问题求助

问题分析与解决方案

核心原因

报错FormatException: //localhost:3030是因为**Uri.http()的第一个参数传入了带http://前缀的地址**(比如http://localhost:3030)。Uri.http()会自动为拼接http://前缀,导致最终生成的URI格式错误(变成http://http://localhost:3030/registration),触发格式异常。

修复步骤

  • 确保registrationUrl的值是不带http:///https://前缀的主机地址,比如直接写localhost:3030。
  • 修正请求代码中的URI构建逻辑:
    // 正确写法:authority参数仅传主机+端口,不带协议
    final response = await http.post(
      Uri.http('localhost:3030', '/registration'),
      headers: {"Content-Type": "application/json"},
      body: jsonEncode(regBody)
    );
    
  • 或者改用Uri.parse()直接传入完整URL,避免手动拼接出错:
    final fullUrl = 'http://localhost:3030/registration';
    final response = await http.post(
      Uri.parse(fullUrl),
      headers: {"Content-Type": "application/json"},
      body: jsonEncode(regBody)
    );
    

额外检查项

  • 确认regBody能被jsonEncode正常序列化,避免因JSON格式错误间接引发异常。
  • 验证后端服务在localhost:3030正常运行,且/registration接口路由配置正确。

内容的提问来源于stack exchange,提问作者Norhassan M. Sarip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:52:11