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

Flutter对接FastAPI登录接口出现422 Unprocessable Entity错误求助

排查Flutter调用FastAPI登录接口返回422错误的步骤

422错误本质是请求数据不符合FastAPI的参数校验规则,结合你的场景,按以下步骤逐一排查:

1. 匹配请求格式与FastAPI接口定义

FastAPI对请求格式的要求严格,必须和接口定义完全匹配:

  • 如果接口用OAuth2PasswordRequestForm(最常用的登录表单模式):
    请求头必须设为Content-Type: application/x-www-form-urlencoded,数据以表单键值对形式传递,而非JSON。Flutter端示例代码:
    import 'package:http/http.dart' as http;
    
    Future<void> submitLogin() async {
      final url = Uri.parse('http://10.0.2.2:8000/login'); // Android模拟器用10.0.2.2替代localhost
      final headers = {'Content-Type': 'application/x-www-form-urlencoded'};
      final body = {
        'username': '你的用户名',
        'password': '你的密码'
      };
      final response = await http.post(url, headers: headers, body: body);
      // 打印响应信息排查
      print('状态码: ${response.statusCode}');
      print('响应内容: ${response.body}');
    }
    
  • 如果接口用JSON请求体(比如基于Pydantic模型):
    请求头设为Content-Type: application/json,并将数据序列化为JSON字符串。Flutter端示例代码:
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    Future<void> submitLogin() async {
      final url = Uri.parse('http://10.0.2.2:8000/login');
      final headers = {'Content-Type': 'application/json'};
      final body = jsonEncode({
        'username': '你的用户名',
        'password': '你的密码'
      });
      final response = await http.post(url, headers: headers, body: body);
      print('状态码: ${response.statusCode}');
      print('响应内容: ${response.body}');
    }
    

2. 严格核对参数名

FastAPI的参数名大小写敏感,比如接口定义的是username,Flutter端传userName或user_name都会触发校验失败。检查你的FastAPI接口代码,确保参数名完全一致:

from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    # 这里参数是username和password,Flutter必须严格对应
    return {"access_token": form_data.username, "token_type": "bearer"}

3. 修正模拟器的网络访问地址

  • Android模拟器无法直接用localhost访问本地服务,必须替换为10.0.2.2(模拟器映射到主机的回环地址);
  • iOS模拟器可以用localhost,但建议直接使用主机的局域网IP(比如192.168.x.x),避免因网络配置导致的访问问题;
  • 同时确保主机防火墙允许uvicorn默认端口(8000)的入站请求。

4. 查看FastAPI返回的错误详情

在Flutter中打印response.body,FastAPI会返回具体的校验错误信息,比如:

{
  "detail": [
    {
      "loc": ["body", "username"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

根据这些信息可以直接定位是参数缺失、格式错误还是名称不匹配。

5. 配置FastAPI的CORS(可选但保险)

虽然422不是跨域错误,但如果CORS配置不当可能间接导致请求异常。给FastAPI添加CORS中间件:

from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 开发环境临时用*,生产环境需指定具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:25:12