使用JavaScript Fetch API向FastAPI后端上传文件时出现422 Unprocessable Entity错误
解决Fetch上传文件到FastAPI出现422 Unprocessable Entity错误
核心问题:参数名不匹配
后端FastAPI接口定义的上传文件参数名为image,但前端FormData里用的键是file,FastAPI无法找到对应参数,导致验证失败返回422。
修复步骤
- 同步前后端参数名:
修改前端FormData的键名,和后端参数名保持一致:
// submit.js 中修改这一行 formData.append("image", image); // 把"file"改成"image"
- 修复响应解析错误:
后端返回的是纯字符串,前端用response.json()会触发解析失败,需改成response.text():
await fetch("http://localhost:8000/caption", { method: "POST", body: formData, }) .then(response => response.text()) // 替换json()为text() .then(result => { console.log("Caption:", result); }) .catch(error => { console.error("Error:", error); });
额外检查项
- 跨域配置:如果前后端端口不同,需在FastAPI中配置CORS,避免跨域拦截:
# api.py 添加CORS配置 from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], # 替换为你的前端实际地址 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
- 规范后端返回格式:建议后端返回JSON结构,更符合API标准,避免解析问题:
# api.py 修改返回逻辑 from fastapi.responses import JSONResponse @app.post("/caption") async def caption(image: UploadFile = File(...)): caption = apiCaption(image) status = await apiSaveData(image, caption) if status: return JSONResponse(content={"caption": caption}) else: return JSONResponse(content={"error": "Something went wrong"}, status_code=500)
此时前端可恢复使用response.json()解析响应。
内容的提问来源于stack exchange,提问作者Jaewon Choi
相关产品推荐
相关产品推荐

