Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't post FormData since Axios 0.25.0 #4406

Closed
TomCorvus opened this issue Jan 19, 2022 · 58 comments
Closed

Can't post FormData since Axios 0.25.0 #4406

TomCorvus opened this issue Jan 19, 2022 · 58 comments

Comments

@TomCorvus
Copy link

TomCorvus commented Jan 19, 2022

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 #3757 on 0.25.0, but I don't know what I have to change in code.

Thanks for your help 👍

@dawidchyrzynski
Copy link

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

@diego-paired
Copy link

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

@azuken
Copy link

azuken commented Jan 21, 2022

Same behaviour with same context (React Native), but with application/x-www-form-urlencoded and URLSearchParams.

I have a bad request 400 error.

Sample :

  const url = `https://XXXX.com/XXXX/token`;
  const params = new URLSearchParams({
    client_id: payload.client_id,
    code: payload.code,
    [...]
  });

  return await axios.post(url, params, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });

@DigitalBrainJS
Copy link
Collaborator

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.

@marf
Copy link

marf commented Jan 31, 2022

Same issue here, could the PR be merged and released, please.

@tapz
Copy link

tapz commented Jan 31, 2022

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

@LarissaGuder
Copy link

Thx bro <3.
I have the same issue here, and just downgrading to "^0.24.0" version, solved my problem.
Waiting for the release.

@Eduardo-lunardi
Copy link

Same issue here, could the PR be merged and released, please.

@jasonsaayman
Copy link
Member

Merged, I will release tonight closing

@TomCorvus
Copy link
Author

Any news about the next release @jasonsaayman?

@falkenhawk
Copy link

@TomCorvus I believe #4448 should be reviewed and merged first

@kocyigityunus
Copy link

kocyigityunus commented Feb 14, 2022

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

@tapz
Copy link

tapz commented Feb 15, 2022

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

@hnikm
Copy link

hnikm commented Feb 15, 2022

@tapz 0.26.0 Doesn't work for me too. Downgraded to 0.24.0 and multipart/form-data is working again!

@raajnadar
Copy link

This issue is due to no boundary in the 'Content-Type'. Downgrading to 0.24.0 adds this automatically.

@kenikori
Copy link

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

@TomCorvus
Copy link
Author

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

@raajnadar
Copy link

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

If you read the docs they say there is no need to add custom content type from our end we need to use a method provided by axios, which will handle the default headers for api calls.

@tapz
Copy link

tapz commented Feb 24, 2022

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.

@hirbod
Copy link

hirbod commented Mar 4, 2022

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

@hirbod
Copy link

hirbod commented Mar 4, 2022

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
  },
});

@c-info
Copy link

c-info commented Apr 26, 2022

Thx bro <3.
I have the same issue here, and just downgrading to "^0.24.0" version, solved my problem.
Waiting for the release.

@Wexleron
Copy link

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

@jasonsaayman
Copy link
Member

@Wexleron please give the latest version a try and let me know if that solves this

@Wexleron
Copy link

@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?

@DigitalBrainJS
Copy link
Collaborator

@Wexleron Can you please run the following code on your platform and then post the result here?

import axios from "axios";
import utils from "axios/lib/utils.js";

const form = new FormData();
const prototype = FormData.prototype;

console.log(
  JSON.stringify({
    VERSION: axios.VERSION,
    client: typeof navigator !== "undefined" && navigator.userAgent,
    node: typeof process !== "undefined" && process.version,
    isFormData: utils.isFormData(form),
    toString: String(form),
    stringTag: form[Symbol.toStringTag],
    constructor: prototype.constructor,
    props: Object.getOwnPropertyNames(prototype)
  })
);

@kocyigityunus
Copy link

@DigitalBrainJS I think he is using react-native. Which doesn't have navigator global.

@Wexleron can you also provide info about the environment? Are you trying to run axios on react native or node or browser ? What are the versions, of react native, node, browser, etc?

@DigitalBrainJS
Copy link
Collaborator

@kocyigityunus Axios uses this kind of check internally (https://stackoverflow.com/questions/39468022/how-do-i-know-if-my-code-is-running-as-react-native) besides React Native must emulate the browser environment, so the main globals should be present.

@Wexleron
Copy link

Wexleron commented Apr 29, 2022

@kocyigityunus

@Wexleron can you also provide info about the environment? Are you trying to run axios on react native or node or browser ? What are the versions, of react native, node, browser, etc?

React Native 17.0.1, Expo 5.4.3, node 16.14.2, running on Android 11 Device. It works now. I am sorry if I am not helpful, I am pretty much in learning process still. Also I am on react native as my secondary skill, I primarily focus on Python & Django backend..

@gavrichards
Copy link

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

@jasonsaayman
Copy link
Member

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

@quantrpeter
Copy link

none of above solutions works in axios@0.27.2 with "react-native": "0.68.2", :-(

@Srh07
Copy link

Srh07 commented Jun 13, 2022

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"

@rizqirizqi
Copy link

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

@VoiceDictionary
Copy link

in my case it as an ID10T error...
//no worky as 'file'
formData.append("file", imgData);

//now it worky as 'image'
formData.append("image", imgData);

ENV
"axios": "^0.27.2",
"expo": "^45.0.6",
"react": "17.0.2",

@rizaldimaulidia
Copy link

rizaldimaulidia commented Oct 29, 2022

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"

@erbaafidotama
Copy link

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"

Thanks for the solution. I follow that code, and i can throw formData to backend.

env:
"axios": "^1.1.3",
"react": "^18.2.0",

@markusand
Copy link

markusand commented Feb 14, 2023

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

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

@jmgrady
Copy link

jmgrady commented Mar 1, 2023

I am having the error with 1.3.4 as well.

@blaisebarre
Copy link

Solved ?

@ibrahimvectra
Copy link

dont think so . I still use 0.24.0

Solved ?

@jaques30081983
Copy link

I tried with 1.4.0 but still have to use that workaround to make it work ->

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

@dreamingofcows
Copy link

dreamingofcows commented Aug 14, 2023

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,
        }
      );
      

@Enliven26
Copy link

For anyone using nextjs 13 beta, axios 1.4.0

CLIENT:
axios.post(url, formData);

SERVER:
await request.formData();

@Enliven26
Copy link

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

@kocyigityunus
Copy link

@Enliven26 make sure to be using the right request headers

@myrs
Copy link

myrs commented Sep 13, 2023

I just switched from 0.24 to 1.5.0, and it works for me in react-native! I'm also stringifying data before appending it to form, i.e.

// payload = <some object>
const formData = new FormData();
formData.append('key', JSON.stringify(payload));
axios.post(url, formData);

@artyorsh
Copy link

It seems the #6056 breaks the transformRequest patch

@piers-smartwyre
Copy link

piers-smartwyre commented Nov 24, 2023

We still require the transformRequest: () => formData workaround in 1.6.2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests