【发布时间】:2022-11-08 13:17:20
【问题描述】:
在前端,我有这个功能:
export const uploadFormData = async (
token: string,
email: string,
formInfo: Array<Object>,
): Promise<any> => {
const formData = new FormData();
formData.append('email', email);
formData.append('form_info', JSON.stringify({ formInfo }));
return fetch(
`${process.env.ENDPOINT}/upload_form_data/`,
{
method: 'POST',
headers: {
Authorization: `Token ${token}`,
},
body: formData,
},
).then((response) => {
console.log(response.body?.getReader());
if (response.status === 404) {
throw Error('Url not found');
}
if (response.status === 422) {
throw Error('Wrong request format');
}
if (response.status !== 200) {
throw Error('Something went wrong with uploading the form data.');
}
const data = response.json();
return {
succes: true,
data,
};
}).catch((error) => Promise.reject(error));
};
在 FastAPI 后端向该端点发送 POST 请求:
@app.post("/api/queue/upload_form_data/")
async def upload_form_data(
email: str = Body(...),
form_info: str = Body(...),
authorization: str = Header(...),
):
return 'form data processing'
但不断抛出以下错误:
在前端:
POST http://localhost:8000/api/queue/upload_form_data/ 422 (Unprocessable Entity)
Uncaught (in promise) Error: Wrong request format
在后端:
POST /api/queue/upload_form_data/ HTTP/1.1" 400 Bad Request
在 Swagger UI(响应正文)中:
{
"detail": [
{
"loc": [
"header",
"authorization"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
导致这些错误的请求有什么问题?
【问题讨论】:
-
422 错误的正文将准确地告诉您缺少什么值以及请求失败的原因;在网络下查看浏览器的开发工具,以查看发送到服务器的实际请求(以及带有正文的响应)。
标签: python reactjs swagger swagger-ui fastapi