jkhsjdhjs / node-fetch-cookies

node-fetch wrapper that adds support for cookie-jars
MIT License
28 stars 16 forks source link

Support for multipart/form-data #17

Open yohanespradono opened 1 year ago

yohanespradono commented 1 year ago

In node-fetch, we can POST data like this

const postData = {
        wpUnicodeCheck: "ℳ𝒲β™₯π“Šπ“ƒπ’Ύπ’Έβ„΄π’Ήβ„―",
        wpAntispam: null,
        wikieditorUsed: "yes"
    };
    var formData = new FormData();
    for ( var key in postData ) {
        formData.append(key, postData[key]);
    }
    console.log(formData)
    let response = await fetch('https://enahwvayvwxi.x.pipedream.net/', {
        method: "POST",
        body: formData
    });

and it converts automatically the data to multipart/form-data. But when I use node-fetch-cookies the remote server gets content-type text/plain and and the body become [object FormData]. Is there anyway to achieve this or this is not supported at this moment?

jkhsjdhjs commented 1 year ago

node-fetch-cookies is based on the v2.x releases of node-fetch, and the native FormData() is only supported by the v3.x releases, as it is only supported by Node.js since version 18. If you want to send forms, there are two possibilities I'm aware of:

  1. application/x-www-form-urlencoded: This is supported by node-fetch v2 using a native Node.js class:

    import fetch from "node-fetch";
    
    const postData = {
        wpUnicodeCheck: "ℳ𝒲β™₯π“Šπ“ƒπ’Ύπ’Έβ„΄π’Ήβ„―",
        wpAntispam: null,
        wikieditorUsed: "yes"
    };
    var formData = new URLSearchParams(postData);
    console.log(formData);
    let response = await fetch('https://enahwvayvwxi.x.pipedream.net/', {
        method: "POST",
        body: formData
    });
  2. multipart/form-data: This is also supported by node-fetch v2, but requires a third-party package:

    import fetch from "node-fetch";
    import FormData from "form-data";
    
    const postData = {
        wpUnicodeCheck: "ℳ𝒲β™₯π“Šπ“ƒπ’Ύπ’Έβ„΄π’Ήβ„―",
        wpAntispam: null,
        wikieditorUsed: "yes"
    };
    var formData = new FormData(postData);
    for ( var key in postData ) {
        formData.append(key, String(postData[key]));
    }
    console.log(formData);
    let response = await fetch('https://enahwvayvwxi.x.pipedream.net/', {
        method: "POST",
        body: formData
    });

    Note that the form-data package doesn't automatically convert null, undefined and boolean values to strings, like the native FormData() does (https://github.com/form-data/form-data/issues/137). Thus, I've wrapped postData[key] in String().

Furthermore, you may want to have a look at this stackoverflow question, which provides answers on when to use which of the form data types.