我尝试使用浏览器将一些数据POST到API方法中。当我使用fastAPI's
Request
对象时,一切正常。但当我使用一个迂腐的模型时,我得到:422 (Unprocessable Entity)
我已经用curl
测试了我的代码,一切正常。
下面是我的fastAPI:
from typing import Optional
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = 'N/A'
@app.post("/test_request")
async def create_item(request:Request):
json = request.json()
return await json
@app.post("/test_pydantic")
async def create_item(item:Item):
return item
if __name__ == '__main__':
uvicorn.run(app='main:app', reload=True, debug=True)
这是我的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>test</h1>
<script>
const person = {
name: 'XXX',
description: 'XXX Desc',
price:200,
tax: 400123598
}
fetch('http://127.0.0.1:8000/test_request', {
method: 'POST',
body: JSON.stringify(person),
contentType: "application/json",
dataType: 'json',
}).then(function(respones) {
return respones.json();
}).then(function(data) {
console.log('Using request', data);
})
fetch('http://127.0.0.1:8000/test_pydantic', {
method: 'POST',
body: JSON.stringify(person),
contentType: "application/json",
dataType: 'json',
}).then(function(respones) {
return respones.json();
}).then(function(data) {
console.log('Using pydantic', data);
})
</script>
</body>
</html>
当从浏览器调用test_pydantic
时,我得到了422
。
1条答案
按热度按时间vxqlmq5t1#
当使用JSON数据调用
fetch
时,您没有设置正确的content-type
。content-type
头位于headers
键下: