Search code examples
react-nativerestaxiosmultipartform-dataform-data

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:

Postman: postman screenshot

Reicht Native Debugging: react native debugger

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

  • This issues is solved in Axios Version 0.27.2 (https://github.com/axios/axios/issues/4460#issuecomment-1115163147)