我正在构建一个简单的 API 来测试数据库。当我使用 get request 时一切正常,但如果我更改为 post,我会收到“无法处理的实体”错误:
这是 FastAPI 代码:
from fastapi import FastAPI
app = FastAPI()
@app.post("/")
def main(user):
return user
Run Code Online (Sandbox Code Playgroud)
然后,我的请求使用 javascript
let axios = require('axios')
data = {
user: 'smith'
}
axios.post('http://localhost:8000', data)
.then(response => (console.log(response.url)))
Run Code Online (Sandbox Code Playgroud)
并使用 Python
import requests
url = 'http://127.0.0.1:8000'
data = {'user': 'Smith'}
response = requests.post(url, json=data)
print(response.text)
Run Code Online (Sandbox Code Playgroud)
我也尝试解析为 json,使用 utf-8 编码,并更改标题。没有什么对我有用。
我试图将一个名为“ethAddress”的值从客户端的输入表单传递到 FastAPI,以便我可以在函数中使用它来生成 matplotlib 图表。
我正在使用 fetch 将输入的文本发布到 Charts.tsx 文件中:
fetch("http://localhost:8000/ethAddress", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ethAddress),
}).then(fetchEthAddresses);
Run Code Online (Sandbox Code Playgroud)
然后我的 api.py 文件设置如下:
#imports
app = FastAPI()
@app.get("/ethAddress")
async def get_images(background_tasks: BackgroundTasks, ethAddress: str):
image = EthBalanceTracker.get_transactions(ethAddress)
img_buf = image
background_tasks.add_task(img_buf.close)
headers = {'Content-Disposition': 'inline; filename="out.png"'}
return Response(img_buf.getvalue(), headers=headers, media_type='image/png')
@app.post("/ethAddress")
async def add_ethAddress(ethAddress: str):
return ethAddress
Run Code Online (Sandbox Code Playgroud)
据我了解,我使用请求将请求正文中的“ethAddress”从客户端传递到后端fetch POST,然后我可以访问@app.post在 FastAPI 中使用已发布的值。然后我将该值作为字符串返回。然后我在路线中使用它GET来生成图表。
我收到此错误:
INFO: 127.0.0.1:59821 - "POST /ethAddress HTTP/1.1" 422 Unprocessable Entity
INFO: 127.0.0.1:59821 …Run Code Online (Sandbox Code Playgroud)