![](/img/trans.png)
[英]How do I download a file returned from FastAPI backend using Fetch API at the frontend?
[英]how can i fetch to fastapi
編輯后
const data = {
text: text,
translateTo: translateTo,
};
await fetch("http://localhost:8000/translate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
backend
origins = [
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
@app.post("/translate")
async def translate(text: str = Body(), translateTo: str = Body()) -> str:
return apiTranslateLang(text, translateTo)
我正確更改了變量的名稱並在后端參數旁邊添加了 Body 然后現在系統顯示此錯誤
CORS 策略已阻止從源“http://localhost:8000/translate”獲取“http://localhost:8000/translate”的訪問權限:請求的資源上不存在“Access-Control-Allow-Origin”header . 如果不透明的響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源。
雖然我接受所有來源,但我真的不知道為什么會導致這個錯誤。
您必須告訴 FastAPI 您的text
和translate
字段是 JSON 正文字段(並且您需要在請求中使用正確的名稱 - translate
而不是translateTo
):
async def translate(text: str = Body(), translate: str = Body()) -> str:
您還可以創建一個 Pydantic model 來描述您的期望 - 這將自動將其預期為 JSON 主體:
from pydantic import BaseModel
class TranslationRequest(BaseModel):
text: str
translate: str
@app.post("/translate")
async def translate(translate_details: TranslationRequest) -> str:
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.