代碼如下所示。
后端
api.py
@app.post("/caption")
async def caption(image: UploadFile = File(...)) -> str:
# produce the caption
caption = apiCaption(image)
# save the image and caption information
status = await apiSaveData(image, caption)
return caption if status else "Something went wrong"
前端
submit.js
export default function SubmitButton({ image }) {
const handleSubmission = async () => {
let formData = new FormData();
console.log(image);
formData.append("file", image);
await fetch("http://localhost:8000/caption", {
method: "POST",
body: formData,
})
.then(response => response.json())
.then(result => {
console.log("Caption:", result);
})
.catch(error => {
console.error("Error:", error);
});
};
return (
<div>
<button disabled={!image} onClick={handleSubmission}>
Submit
</button>
</div>
);
}
服務器不斷顯示:
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity) error
我真的不知道為什么,錯誤代碼很模糊,所以無法理解。
uj5u.com熱心網友回復:
確保在客戶端使用與服務器端相同的 密鑰(引數名稱)UploadFile。在您的情況下,即image,如代碼的這一行所示:
async def caption(image: UploadFile = File(...))
^^^^^
因此,在客戶端,將檔案附加到FormData實體時,您應該使用該密鑰:
formData.append("image", image);
請查看此答案以獲取更多詳細資訊和示例。此外,為了將來參考,正如您所說, 422 狀態代碼并不是很模糊。422 回應正文將包含有關缺少哪些欄位或與預期格式不匹配的錯誤訊息,這將幫助您解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508888.html
標籤:javascriptPython拿来快速API表单数据
下一篇:變數在IF條件內不生效
