我正在try 使用post方法将一个图像从客户端(reactJS)上传到fastAPI
这是我的客户
const [img, setImg] = useState(null)
const onImageUpload = (e) => {
console.log(e.target.files[0])
setImg(e.target.files[0])
}
const handleChange = () => {
if (!img) setErr("please upload an image")
else {
let formData = new FormData();
let token = localStorage.getItem("TikToken")
formData.append(
"token",
token
)
formData.append(
"pic",
img,
img.name
)
console.log(formData)
axios({
method: 'post',
url: "http://localhost:8000/profile/pic/",
data: formData
})
.then(function(response) {
console.log(response);
})
}
}
这是我的fastAPI函数
@app.post("/profile/pic/")
async def setpic(token: str, pic:bytes = File(...)):
print(pic)
image = Image.open(io.BytesIO(pic))
image.show()
# response = await store_profile_image(form, str(base64.b64encode(form)))
return "response"
我遇到了错误422(无法处理的实体)
这就是错误所在
Edit:1 Uncaught (in promise)
AxiosError {message: 'Request failed with status code 422', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_REQUEST"
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
message: "Request failed with status code 422"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response: {data: {…}, status: 422, statusText: 'Unprocessable Entity', headers: {…}, config: {…}, …}
[[Prototype]]: Error
我做错了什么?
编辑:
我判断了错误主体(响应>;数据>;详细信息)
我找到了这个
detail: Array(1) 0:
loc: (2) ['query', 'token']
msg: "field required"
type: "value_error.missing"
我将axios请求中的数据更改为
我在错误的身体里找到了这个
detail: Array(2)
0:
loc: (2) ['query', 'token']
msg: "field required"
type: "value_error.missing"
[[Prototype]]: Object
1:
loc: (2) ['body', 'pic']
msg: "field required"
type: "value_error.missing"
[[Prototype]]: Object
length: 2