我正在尝试通过 Axios 上传文件(版本 ^0.26.0
) 在 React Native (版本 0.66.4
) 中使用以下代码:
const formData = new FormData();
formData.append('image', {
uri: 'aFilePathProvidedByTheImagePicker',
name: 'file.jpg',
type: 'image/jpg'
});
const response = await this.axiosInstance.put('aCustomUrl', formData, {
headers: {
'Content-Type': 'multipart/form-data;',
},
});
但它总是失败,状态代码为 400。我尝试使用 Postman 工作正常。
经过一些调试并比较 axios 和 postman 的请求后,我发现 Content-Length
标头丢失。此外,未提供 Content-Type
中的边界
。请参阅下面的屏幕截图:
邮递员:
Reicht 本机调试:
我还阅读了有关 formData.getLengthSync()
的内容,但在 React Native 中它会导致错误 formData.getLengthSync 不是一个函数
有人知道吗一个这个问题的解决方案?
根据此 帖子 将 axios 降级到版本 0.24.0
作为一种解决方法。
(出于调试目的,我使用了 fetch-api 中的构建,它按预期工作。但我更喜欢使用 axios 来使用带有请求和响应的共享实例 拦截器)
I'm trying to upload a file via Axios (Version ^0.26.0
) in React Native (Version 0.66.4
) with the following code:
const formData = new FormData();
formData.append('image', {
uri: 'aFilePathProvidedByTheImagePicker',
name: 'file.jpg',
type: 'image/jpg'
});
const response = await this.axiosInstance.put('aCustomUrl', formData, {
headers: {
'Content-Type': 'multipart/form-data;',
},
});
But it always fails with the status code 400. I tried the requested endpoint with Postman and it works fine.
After some debugging and comparing the requests from axios and postman I found out that the Content-Length
header is missing. Also a boundary
in Content-Type
isn't provided. See the screenshots below:
Postman:
Reicht Native Debugging:
I also read about the formData.getLengthSync()
but in react native it leads to the error formData.getLengthSync is not a function
Does anyone has a solution for this issue?
According to this post downgrading axios to version 0.24.0
works as a workaround.
(for debugging purpose I used the build in fetch-api which works as expected. but I'd prefer using axios for using a shared instance with request and response interceptors)
发布评论
评论(2)
此问题在 Axios 版本 0.27.2 中得到解决(https://github.com /axios/axios/issues/4460#issuecomment-1115163147)
This issues is solved in Axios Version 0.27.2 (https://github.com/axios/axios/issues/4460#issuecomment-1115163147)
您的代码应该可以工作,但您可以尝试将内容类型添加到标头
Your code should work but you could try to add content-type to headers