'Axios in React Native doesn't provide Form-Data headers
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:
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)
Solution 1:[1]
This issues is solved in Axios Version 0.27.2 (https://github.com/axios/axios/issues/4460#issuecomment-1115163147)
Solution 2:[2]
Your code should work but you could try to add content-type to headers
"Content-Type": "multipart/form-data; boundary=" + formData .getBoundary(),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Marco Weber |
Solution 2 | luong vy |