node-fetch-cookies
node-fetch-cookies copied to clipboard
Support for multipart/form-data
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?
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:
-
application/x-www-form-urlencoded
: This is supported bynode-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 });
-
multipart/form-data
: This is also supported bynode-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 convertnull
,undefined
and boolean values to strings, like the nativeFormData()
does (https://github.com/form-data/form-data/issues/137). Thus, I've wrappedpostData[key]
inString()
.
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.