FastAPI与Axios调用出现422 Unprocessable Entity错误求助
问题排查与解决方案
核心问题分析
422错误提示所有请求体字段缺失,结合前后端代码,主要存在以下几个关键问题:
1. 前端请求头拼写错误
在api.js的请求拦截器中,ContentType字段名拼写错误,正确的HTTP头字段应为Content-Type。FastAPI依赖该头部识别请求体格式,错误的字段名会导致后端无法解析JSON请求体,进而判定所有字段缺失。
2. 后端Pydantic模型设计不合理
UserBase模型中id被定义为必填int类型,但用户注册时ID应由后端(数据库自增逻辑)生成,不应由前端传入,这会引发不必要的验证错误。
3. 前端注册数据赋值错误
在handleRegistration中,email被错误赋值为inputs.password,虽不是当前422错误的直接原因,但会导致后续邮箱验证失败,需同步修正。
具体修复步骤
修复前端请求头
修改api.js中的请求拦截器,修正Content-Type字段名:
api.interceptors.request.use((config) => { config.headers = { Accept: 'application/json', 'Content-Type': "application/json" // 修正字段名拼写 }; return config; });
优化后端Pydantic模型
创建专门的UserCreate模型用于接收注册请求,避免复用包含id的UserBase:
# user.py from pydantic import BaseModel from .document import DocumentBase # 用于接收注册请求的模型,无需id字段 class UserCreate(BaseModel): username: str password: str email: str phone_number: str # 用于返回或映射数据库模型的基础模型 class UserBase(BaseModel): id: int username: str email: str phone_number: str documents: list[DocumentBase] = [] class Config: arbitrary_types_allowed = True orm_mode = True
修改auth.py中的接口,使用UserCreate接收请求数据:
# auth.py from .user import UserCreate # 导入新的请求模型 @router.post("/register", response_model=UserBase) # 指定返回模型结构 def register(data: UserCreate, _db: Session = Depends(get_db)): # 检查用户是否已存在 user = _db.query(User).filter(User.email == data.email).first() if user is not None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="User with this email already exist" ) new_user = User() new_user.username = data.username new_user.password = get_hashed_password(data.password) new_user.email = data.email new_user.phone_number = data.phone_number _db.add(new_user) _db.commit() _db.refresh(new_user) # 刷新获取数据库生成的id return new_user
修复前端数据赋值错误
修改handleRegistration中的new_user对象,正确赋值邮箱字段:
let new_user = { username: inputs.username, password: inputs.password, email: inputs.email, // 修正为正确的邮箱输入值 phone_number: inputs.phone }
额外排查建议
- 利用浏览器开发者工具的网络标签,查看请求的
Payload和Headers,确认请求体是否正确发送、Content-Type头是否存在且格式正确。 - 先通过FastAPI自动生成的文档页面(
http://localhost:8000/docs)测试接口,验证后端逻辑是否正常,快速排除前端问题。
内容的提问来源于stack exchange,提问作者mdh75
相关产品推荐
相关产品推荐

