FastAPI在来自Next.js的 fetch发出的POST请求中,尽管与Pydantic模型匹配,仍返回422不可处理的实体
我正在从Next.js 14客户端向FastAPI端点发送POST请求。请求体与我的Pydantic模型完全匹配,但我一直得到一个 422 Unprocessable Entity 而不是一个 200。
预期: 端点接受JSON并返回创建的对象。
实际: {"detail":[{"loc":["body","email"],"msg":"field required"}]}
FastAPI端点:
@app.post("/contacts")
async def create_contact(contact: Contact):
return contact
Next.js fetch:
await fetch("/api/contacts", {
method: "POST",
body: JSON.stringify({ email: "[email protected]" }),
});
我尝试过的办法: 确认网络标签中的载荷,检查模型字段名是否匹配。将请求体完全移除也会得到相同的错误。
解决方案
我写了一个最小可运行的代码,它也给出 422 Unprocessable Entity
但在我添加
headers: {"Content-Type": "application/json"}
时就能工作
我也使用了完整的URL "http://localhost:8000/contacts" 但我没有检查这是否重要。
用于测试的完整代码:
app/page.tsx
// npx create-next-app@latest my-app
// cd my-app
// npm run dev
"use client";
export default function Page() {
async function send() {
const res = await fetch("http://localhost:8000/contacts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "[email protected]",
}),
});
const data = await res.json();
console.log(data);
}
return (
<div>
<h1>Next.js + FastAPI</h1>
<button onClick={send}>Send request</button>
</div>
);
}
main.py
# uvicorn main:app --reload --port 8000
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# IMPORTANT for browser requests
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class Contact(BaseModel):
email: str
@app.post("/contacts")
async def create_contact(contact: Contact):
print(f"{contact=}")
return contact
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。