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

Flutter Web无法发起HTTP请求的问题求助

Flutter Web无法发起HTTP请求问题排查与解决

错误信息

后端日志

127.0.0.1:52159 - "POST /signIn HTTP/1.1" 422 Unprocessable Entity

前端报错

ClientException: XMLHttpRequest error., uri=http://127.0.0.1:8000/signIn

代码详情

后端(FastAPI)

登录接口代码:

@app.post("/signIn", response_model=ApiResponse)
def login(auth: AuthModel):
    response = au.signIn(auth)
    return response

数据模型:

  • AuthModel
class AuthModel(BaseModel):   
    uid: str = None   
    email: str   
    password: str   
    name: str = None
  • ApiResponse
class ApiResponse(BaseModel):   
    message: str   
    description: str = None   
    success: bool   
    status_code: int   
    data: dict = {}

前端(Flutter)

登录请求代码:

Future<bool?> signIn() async {
  try {
    final response = await http.post(
      Uri.http(_url, '/signIn'),
      body: authData,
      headers: {
        "Access-Control-Allow-Origin": "*"
      }
    );
    print(response.body);
    SharedPrefs.setToken(json.decode(response.body)['data']['token']);
    return true;
  } catch (e) {
    print(e);
    return false;
  }
}

环境信息

  • Flutter(master通道,3.12.0-11.0.pre.12,运行在macOS 13.4.1 22F82 darwin-x64,语言区域en-DZ)
  • Python v3.11
  • FastAPI v0.100.0

问题原因及解决办法

  1. 422错误核心:请求参数不匹配
    FastAPI返回422状态码说明请求参数不符合AuthModel的校验规则,常见原因是参数格式不兼容:Flutter http.post默认发送x-www-form-urlencoded格式数据,而FastAPI默认期望JSON格式。

  2. 修复前端请求格式
    修改前端代码,发送JSON格式数据:

Future<bool?> signIn() async {
  try {
    final response = await http.post(
      Uri.http(_url, '/signIn'),
      body: json.encode(authData), // 将数据转为JSON字符串
      headers: {
        "Content-Type": "application/json", // 指定内容类型为JSON
      }
    );
    print(response.body);
    SharedPrefs.setToken(json.decode(response.body)['data']['token']);
    return true;
  } catch (e) {
    print(e);
    return false;
  }
}
  1. 解决跨域问题
    前端设置Access-Control-Allow-Origin无效,该响应头需由后端返回。在FastAPI中添加跨域中间件:
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 配置跨域(开发环境可设为*,生产环境需指定具体域名)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
  1. 额外检查点
  • 确认_url值为127.0.0.1:8000,与后端服务地址一致
  • 打印authData具体内容,验证字段是否与AuthModel匹配(如是否存在拼写错误)
  • 用Postman直接调用后端/signIn接口,传入正确JSON参数,确认后端接口本身正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:05:14