如何将 JSON 数据从 JavaScript 前端发布到 FastAPI 后端?
- 2024-12-25 08:51:00
- admin 原创
- 120
问题描述:
我正在尝试将一个名为“ethAddress”的值从客户端的输入表单传递给 FastAPI,以便可以在函数中使用它来生成 matplotlib 图表。
我正在使用 fetch 将输入的文本发布到 Charts.tsx 文件中:
fetch("http://localhost:8000/ethAddress", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ethAddress),
}).then(fetchEthAddresses);
然后我设置我的 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
据我了解,我使用请求将请求主体中的“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 - "GET /ethAddress HTTP/1.1" 422 Unprocessable Entity
我也尝试过将客户端的获取方法从 POST 改为 GET。但出现以下错误:
TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
解决方案 1:
您在端点中定义的方式ethAddress
应作为查询参数;因此422 Unprocessable Entity
出现错误。根据文档:
当您声明不属于路径参数的其他函数参数时,它们会被自动解释为“查询”参数。
要将参数解释为 JSON,您需要使用以下选项之一。
选项 1
创建Pydantic 模型:
from pydantic import BaseModel
class Item(BaseModel):
eth_addr: str
@app.post('/')
async def add_eth_addr(item: Item):
return item
FastAPI 期望主体如下:
{
"eth_addr": "some addr"
}
使用 Fetch API 执行 HTTP 请求:
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"eth_addr": "some addr"
}),
})
.then(resp => resp.json()) // or, resp.text(), etc.
.then(data => {
console.log(data); // handle response data
})
.catch(error => {
console.error(error);
});
选项 2
使用Body
参数类型:
from fastapi import Body
@app.post('/')
async def add_eth_addr(eth_addr: str = Body()):
return {'eth_addr': eth_addr}
FastAPI 期望主体如下:
"some addr"
使用 Fetch API 执行 HTTP 请求:
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify("some addr"),
})
.then(resp => resp.json()) // or, resp.text(), etc.
.then(data => {
console.log(data); // handle response data
})
.catch(error => {
console.error(error);
});
选项 3
由于您只有一个主体参数,因此您可能需要使用特殊Body
参数embed
:
from fastapi import Body
@app.post('/')
async def add_eth_addr(eth_addr: str = Body(embed=True)):
return {'eth_addr': eth_addr}
FastAPI 期望主体如下:
{
"eth_addr": "some addr"
}
使用 Fetch API 执行 HTTP 请求:
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"eth_addr": "some addr"
}),
})
.then(resp => resp.json()) // or, resp.text(), etc.
.then(data => {
console.log(data); // handle response data
})
.catch(error => {
console.error(error);
});
相关答案,包括有关如何发布 JSON 数据的 JavaScript 示例,可在此处、此处以及此处和此处找到。当涉及在同一请求中发布 JSON 数据和文件时,此答案也可能有用。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD