axios: Can't post FormData since Axios 0.25.0

Describe the issue

I can’t post FormData since "axios": "^0.25.0",

Error: Request failed with status code 400

Example Code

export const client = axios.create({
        baseURL: URL_API,
        withCredentials: true,
        responseType: 'json',
	timeout: 30000,
});

const params = new FormData();

params.append('name', data.model);
params.append('idFuel', data.idFuel);
params.append('power', data.idPower);

client.post(`/app/society/${idSociety}/vehicle`, params, { headers: { "Content-Type": "multipart/form-data" } })

Expected behavior, if applicable

That it works

Environment

  • Axios Version: 0.25.0
  • Node.js Version: v14.17.6
  • OS: iOS 15, Android 11 (But on all platforms and versions)
  • Additional Library Versions: React Native 0.64.3

Additional context/Screenshots

No problem with "axios": "^0.24.0",

I saw this PR https://github.com/axios/axios/pull/3757 on 0.25.0, but I don’t know what I have to change in code.

Thanks for your help 👍

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 34
  • Comments: 68 (4 by maintainers)

Most upvoted comments

It works for me:

const formData = new FormData();
...
const response = await networking.post('/URL', formData, {
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  transformRequest: (data, headers) => {
    return formData;
  },
});

Versions: react-native: 0.67.2 axios: 0.26.0

This is a shorter form, since it is still needed in 0.26.1

axios.post(url, formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  transformRequest: formData => formData,
})

The headers value might only be needed if you have modified the default Content-Type for axios. (just a guess since I have read that axios should set the correct Content-Type based on the FormData type)

In which axios version will the fix that closed this issue be released?

Just found out, thanks to this comment: https://stackoverflow.com/questions/56235286/react-native-post-form-data-with-object-and-file-in-it-using-axios/71116822#71116822

that you don’t need to return “formData” in your transformRequest, it is just enough to return “data”.

const formData = new FormData();
...
const response = await networking.post('/URL', formData, {
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  transformRequest: (data) => {
    return data; // thats enough
  },
});

I have added transformRequest according to @Wexleron answer. But i have still can’t fix this issue. But after quite a while I have found a solution to fix this issue, the key is don’t set “Conten-type: multipart/form-data” manually, just remove it, let axios create that header automatically. The folowing code will fix this issue :

const formData = new FormData();
...
const response = await axios.post('/URL', formData, {
  transformRequest: () => formData,
});

Env: “axios”: “^1.1.3” “react”: “18.2.0”

This problem appears to be due to someone recklessly optimizing the isFormData function in the utils.js file. This could break form detection logic in a non-browser environment where FormData is not a native object that can be recognized by the Object.prototype.toString method. Fixed in #4413 with some additional benefits.

We have the same issue, with the following code:

  const data = new FormData();
  data.append(name, {
    uri: toUri(filePath),
    name: fileName,
    type,
  });
  return await post<T>(endpoint, data, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data;',
      'cache-control': 'no-cache',
    },
  });

The backend throws a Multipart: Boundary not found error

Merged, I will release tonight closing

Why are these kind of useless “optimizations” even done? Why change something that works? Nobody will see any speed improvement.

0.26.0 does not work with React Native. Could someone please test the changes with RN before releasing?

Hi Guys, I tried all the solutions that were added in this discussion, but I still find myself having problems, Axios shows error 404, I will leave an excerpt of my code, which are very similar to some of the examples mentioned here, about the versions, initially I’m using the most current ones from both Expo and React Native. The point is that the code would work very well on the web, and it does, when I run the react native web project, it works perfectly. Has this problem really been fixed? It wouldn’t be the first issue I’ve commented on in the last week. Any hope? (I did several downgrades, but I didn’t feel any difference) Furthermore Axios only displays a 404 NetworkError error, it doesn’t specify much about it, even using catch for debugs.

const pickImage = async () => {
        try {
            const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
            if (status !== 'granted') {
                alert('Desculpe, precisamos da permissão para acessar sua galeria!');
                return null;
            }
            const resultImagePicker = await ImagePicker.launchImageLibraryAsync({
                mediaTypes: ImagePicker.MediaTypeOptions.Images,
                allowsEditing: true,
                aspect: [4, 3],
                quality: 1,
                base64: true,
            })
            console.log('Image ResultPickerImage>', resultImagePicker)
            if (!resultImagePicker.canceled) {
                setImage(resultImagePicker?.assets[0])
                const URIImage = resultImagePicker?.assets[0].uri
                const base64 = resultImagePicker?.assets[0].base64
                const resultFecthImageURI = await fetch(URIImage)
                const ImageFileObject = resultImagePicker.assets[0]
                const BlobResultFecthImageURI = await resultFecthImageURI.blob()
                const fileNewFile: any = new File([BlobResultFecthImageURI], JSON.stringify(resultImagePicker.assets[0]?.fileName), { type: `${resultImagePicker.assets[0].mimeType}` })
                const config: AxiosRequestConfig = {
                    headers: {
                        'Accept': 'application/json',
                        'Authorization': `Bearer ${tokenByStorage}`,
                        'Content-type': 'multipart/form-data',
                    },
                    transformRequest: () => {
                        return formData
                    },
                };
                formData.append('CurrentPage', 1);
                formData.append('PageSize', 1);
                formData.append('Search', JSON.stringify(fileNewFile));

                const response = await api.post('/MissingPersonReport/findFace', formData, config)

                if (response) {
                    console.log('Response de Picker imagem >', response)
                }
            }

        } catch (error) {
            console.error(error)
            console.log(error)
            throw (error);
        }
    }
  • Package.json
    "axios": "1.6.7",
    "expo": "^51.0.38",
    "react": "18.2.0",

image

React Native now works as of Axios 0.27.0! No more inexplicable 400 errors.

I’m not going to add any bubble gum code to fix a bug in axios. I’ll just wait for a version that actually works. Not even sure if there is any need to upgrade 0.24.0 any time soon as this version works just fine.

Any news about the next release @jasonsaayman?

Thx bro ❤️. I have the same issue here, and just downgrading to “^0.24.0” version, solved my problem. Waiting for the release.

This is a shorter form, since it is still needed in 0.26.1

axios.post(url, formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  transformRequest: formData => formData,
})

The headers value might only be needed if you have modified the default Content-Type for axios. (just a guess since I have read that axios should set the correct Content-Type based on the FormData type)

In which axios version will the fix that closed this issue be released?

Works perfectly for me

@kenikori is it the official way to post FormData with Axios now? Or is it just a crutch?

if you are having any issues with multipart form data upload on react native. please check this answer.

For anyone still struggling with this, the latest axios version has a postForm function (docs), which solved the problem for me.

Just tested 0.27.2 and it’s working as expected now.

@jasonsaayman Hi, schteff’s tip worked for me. Simply updating the Axios did not.

Thanks to Schteff.

The tip:

This is a shorter form, since it is still needed in 0.26.1

axios.post(url, formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  transformRequest: formData => formData,
})

The headers value might only be needed if you have modified the default Content-Type for axios. (just a guess since I have read that axios should set the correct Content-Type based on the FormData type)

In which axios version will the fix that closed this issue be released?

Axios 0.26.1 This bug still occurs… Env:

  • React native 0.67.4
  • Axios 0.26.1
  • React 17.0.2

Still having this error with 1.3.3. I need to still use this workaround.

axios.post(url, formData, {
   transformRequest: () => formData,
})

none of above solutions works in axios@0.27.2 with “react-native”: “0.68.2”, 😦

Please donrt use 0.27.0 that was a borked release, please use the latest version

I’ve tested 0.27.2 today in React Native and found it works, where it previously wasn’t.

I’m having the same problem since updating to 0.25.0.

Thanks @dan-pugsley, I can confirm that using the postForm api worked for me.

For anyone still struggling with this, the latest axios version has a postForm function (docs), which solved the problem for me.

Thanks @dan-pugsley

@bot-leo Is the backend API actually returning a 404?

If so, what URL is the client attempting to fetch that it is 404? Why would one client get 404 when another gets a valid response (200)?

The response is not a client/react-native/axios thing. It is the server’s response to a client request. So at the server end, what is different between the RN/axios request and other clients that do not get a 404?

Hi Guys, I tried all the solutions that were added in this discussion, but I still find myself having problems, Axios shows error 404

If you are getting a 404 response, that means the URL you are trying to make a request to does not exist.

Your code api.post('/MissingPersonReport/findFace', ...) is going to a server, and that server is replying that the request you are making has no endpoint configured (it is “404 - NOT FOUND”).

So check your server logs to see what is happening. Check your configuration of api to validate the host and port of the API server.

Your code is attempting to call:

https://api-abcd-prd.azurewebsites.net//MissingPersonReport/findFace

Is that the URL you expect it to be?

I also see in your JS console output:

image

So maybe you don’t have your api configured correctly? Why is 192.168.15.101:8081 showing up?

I am using Axios 1.4 (also tried with 1.3.4) and the work around still does not work for me:

If I look at the actual request payload it still just sends the string “[object Object]” instead of the actual data… help…

axios.post(
        `/url`,
        applicationFormData,
        {
          transformRequest: () => applicationFormData,
        }
      );
      

convert the data into string (for example using JSON.stringify()) or blob before appending to formdata object

dont think so . I still use 0.24.0

Solved ?

I’ve tested 0.27.2 today in React Native and found it works, where it previously wasn’t.

I’ve tested 0.27.2 with “react-native”: “0.67.4” and I can confirm this works, without the need to use “transformRequest”

Thanks @kenikori Wish I would’ve seen that before I wasted 5 frickin hours understanding, why image uploads are broken for me out of the blue

2 days for me, then i give up for 2 weeks and take a rest:-) I did exactly by the book, every help on internet was exactly same and didnt functioned. I still ahve problems. but at least I know wheres the catch