Skip to content

Support other FormData implementations #4610

Closed

Description

@verhovsky

Is your feature request related to a problem? Please describe.

It's related to the problem of sending multipart/form-data with Axios on Node.js

Describe the solution you'd like

I would like to be able to do

const axios = require('axios');
const { FormData } = require('formdata-node');
const form = new FormData();
axios.post('http://localhost:8888', form)

Describe alternatives you've considered

N/A

Additional context

got recommends using formdata-node. Axios recommends form-data.

I would like to use formdata-node with both because I want to use both got and Axios and I don't want people reading the code to need to notice that there's two different libraries used for FormData. Also formdata-node has a table saying that form-data's FormData doesn't have a bunch of methods that the browser's does. I tried using formdata-node with Axios

cd /tmp
mkdir axios-form-test
cd axios-form-test
npm init -y
npm install axios
npm install formdata-node
node
const axios = require('axios');
const { FormData } = require('formdata-node');

const form = new FormData();
form.append('my_field', 'my value');
form.append('my_other_field', 'my second value');

axios.post('http://localhost:8888', form)

and got an error

Uncaught:
Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream
    at createError (/private/tmp/axios-test/node_modules/axios/lib/core/createError.js:16:15)
    at dispatchHttpRequest (/private/tmp/axios-test/node_modules/axios/lib/adapters/http.js:98:23)
    at new Promise (<anonymous>)
    at httpAdapter (/private/tmp/axios-test/node_modules/axios/lib/adapters/http.js:48:10)
    at dispatchRequest (/private/tmp/axios-test/node_modules/axios/lib/core/dispatchRequest.js:58:10)
    at Axios.request (/private/tmp/axios-test/node_modules/axios/lib/core/Axios.js:108:15)
    at Axios.<computed> [as post] (/private/tmp/axios-test/node_modules/axios/lib/core/Axios.js:140:17)
    at Function.wrap [as post] (/private/tmp/axios-test/node_modules/axios/lib/helpers/bind.js:9:15) {
  config: { [...]

Activity

  1. octet-stream commented on Apr 27, 2022

    @octet-stream

    I'd rather recommend to use form-data-encoder package to do so. That way Axios will have support for multipart/form-data encoding in general, regardless of what package you choose - either formdata-node, or formdata-polyfill, or something else (except for form-data package, because it's not spec-compliant).

  2. jasonsaayman commented on Apr 27, 2022

    @jasonsaayman
    Member

    Latest version of axios will handle this for you without any need of installing a package, please check the latest docs

  3. verhovsky commented on Apr 27, 2022

    @verhovsky
    Author

    Where are the latest docs? I checked

    https://github.com/axios/axios-docs/blob/master/posts/en/urlencoded.md#form-data

    https://github.com/axios/axios-docs/blob/master/posts/en/req_config.md

    And neither mention it. The latter doesn't even mention form-data, it just says FormData is browser only. I also noticed the former doesn't mention that URLSearchParams can be used on Node since Node 10, it just tells you to import it from a library.

  4. DigitalBrainJS commented on Apr 27, 2022

    @DigitalBrainJS
    Collaborator

    I was going to add support for it (both form-data and formdata-node) when I did a PR with the FormData enhancement for Axios about six months ago, but then I decided to keep only form-data for a while, since the package was pretty new. Most likely in the near future we should replace the default form-data module with formdata-node, or create our own simple stream encoder, but writing it in ES5 is painful.

    Currently, you can use a custom transform to support this package (both form-data & formdata-node simultaneously)

    import axios from "axios";
    import { Readable } from "stream";
    import { FormDataEncoder } from "form-data-encoder";
    import { FormData } from "formdata-node";
    import FormDataLegacy from "form-data";
    
    ((transforms) => {
      const isFormData = (thing) =>
        thing &&
        Object.prototype.toString.call(thing) === "[object FormData]" &&
        thing.values;
    
      transforms.unshift((data, headers) => {
        if (isFormData(data)) {
          const encoder = new FormDataEncoder(data);
          Object.assign(headers, encoder.headers);
          return Readable.from(encoder);
        }
    
        return data;
      });
    })(axios.defaults.transformRequest);
    
    // use axios with it
    (async()=>{
      function test(form) {
        form.append("test", 123);
        return axios.post("https://httpbin.org/post", form).then(({data})=> console.log(data), console.warn);
      }
    
     console.log(axios.VERSION);
     // formdata-node
     await test(new FormData());
     // formdata
     await test(new FormDataLegacy());
    })();
  5. verhovsky commented on Apr 28, 2022

    @verhovsky
    Author

    Node 18 was just released and it comes with a native FormData and that also should be supported. This is what I get with axios 0.27.2

    $ node
    Welcome to Node.js v18.0.0.
    Type ".help" for more information.
    > const axios = require('axios');
    undefined
    > await axios.post('localhost:8888', new FormData())
    (node:24059) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
    (Use `node --trace-warnings ...` to show where the warning was created)
    Uncaught:
    [AxiosError: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream] {
      code: 'ERR_BAD_REQUEST',
      config: {
  6. octet-stream commented on Apr 28, 2022

    @octet-stream

    Most likely in the near future we should replace the default form-data module with formdata-node, or create our own simple stream encoder, but writing it in ES5 is painful.

    Hmm. I think if you implement Blob support in Axios for Node.js adapter it should be relatively simple, because you can just convert FormData to blob like this: https://github.com/jimmywarting/FormData/blob/master/formdata-to-blob.js

    To support Blob, however, Axios need to be able to read both ReadableStream and Readable (in case if somebody will use [email protected]) produced by Blob.prototype.stream() method, because other methods (.text() and .arrayBuffer()) would not be memory efficient.

  7. changed the title [-]Support formdata-node[/-] [+]Support other FormData implementations[/+] on Apr 29, 2022
  8. jimmywarting commented on Jul 6, 2022

    @jimmywarting

    It is relative straight forward to create a NodeJS stream using: node:stream.Readable.from(blob.stream()) if you still depend on that nodejs stuff. the fetch spec have recently changed to be acceptable of asyncIterator to support both whatwg & NodeJS streams, think you should support async iterators too...

    • This tiny "formdata to blob" stuff that i have built is also what Deno and node-fetch is using in there impl.
    • undici use parts of it (the iteration that yields all chunks)

    I think we could start with adding support for Blob's as an acceptable data payload...


    On the other hand: if we switch the adapter to use built in fetch in NodeJS v18 or using Undici or node-fetch
    then it would be relative simple to support both blobs and formdata and just let this slide in as it can handle it for you so that you do not have to encode formdata or do anything special to support blobs either...
    using fetch have also the benefit to make it work in service worker too... and cloudflare/Deno

    maybe ppl should be able to bring in there own fetch impl if they wishes. Maybe it's time to ditch the old node:http & node:https core adapter module.

  9. Dany-C commented on Nov 13, 2022

    @Dany-C

    With Node 18, you can now use the native globals FormData and fetch.

    Notices :

    • Those are experimental features
    • Do not add headers to the request

    image

    Below a simple exemple with 2 little text files

    `
    const url = 'insert-your-url-here';
    const formData = new FormData();

    const blobTxt1 = new Blob(['test text 1'], {type:'multipart/form-data'});
    const blobTxt2 = new Blob(['test text 2'], {type:'multipart/form-data'});

    formData.append(
    'test txt 1',
    blobTxt1,
    'testTxt1.txt'
    );

    formData.append(
    'test txt 2',
    blobTxt2,
    'testTxt2.txt'
    );

    const resultTestTxt = await fetch(url, {
    method: 'POST',
    body: formData,
    });
    `

    Dany

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions