Error [ERR_REQUIRE_ESM] when working with FormData #1417
Replies: 2 comments
-
Hmm, you are not suppose to add the content-length in manually. The byte length will be automatically calculated for you when we iterating over all the formdata fields, so you shouldn't add the content-length yourself also, you shouldn't add the content-type manually like this cuz it needs a boundary meta data in the header in order to properly parse it. like here is an working example: import fetch from 'node-fetch'
import { fileFromSync } from 'fetch-blob/from.js'
import { FormData } from 'formdata-polyfill/esm.min.js'
const file = fileFromSync('./fetch-issue-1416/index.js')
const fd = new FormData()
fd.append('file', file)
fd.set('other data', 'some data')
const res = await fetch(`https://httpbin.org/post`, {
method: 'POST',
headers: {
Authorization: `abc123`
},
body: fd
})
const json = await res.json()
console.log(json) with the output being: {
args: {},
data: '',
files: {
file: "import fetch from 'node-fetch'\n" +
"import { fileFromSync } from 'fetch-blob/from.js'\n" +
"import { FormData } from 'formdata-polyfill/esm.min.js'\n" +
'\n' +
"const file = fileFromSync('./fetch-issue-1416/index.js')\n" +
'const fd = new FormData()\n' +
"fd.append('file', file)\n" +
"fd.set('other data', 'some data')\n" +
'\n' +
'const res = await fetch(`https://httpbin.org/post`, {\n' +
" method: 'POST',\n" +
' headers: {\n' +
' Authorization: `abc123`\n' +
' },\n' +
' body: fd\n' +
'})\n' +
'\n' +
'const json = await res.json()\n' +
'console.log(json)'
},
form: { 'other data': 'some data' },
headers: {
Accept: '*/*',
'Accept-Encoding': 'gzip,deflate,br',
Authorization: 'abc123',
'Content-Length': '742',
'Content-Type': 'multipart/form-data; boundary=----5570292816803601957728722138',
Host: 'httpbin.org',
'User-Agent': 'node-fetch'
},
json: null,
origin: 'xx.xxx.xx.xx',
url: 'https://httpbin.org/post'
} |
Beta Was this translation helpful? Give feedback.
-
Plus the error message you gave is not about formdata, it's about ESM to use esm, you basically need to add import('node-fetch').then({ default: fetch, Headers, Response, Request } => {
fetch(url).then(...)
}) more about this in #1279 |
Beta Was this translation helpful? Give feedback.
-
Trying to find a working NodeJs combination for POSTing a
multipart/form-data
, and as mentioned in the docs, I tried a few options includingformdata-polyfill
andformdata-node
, and also by using(await new Response(new URLSearchParams()).formData()).constructor
, In all 3 cases I was unable to run the code, with the following error (or similar):I am getting that error on both v2 and v3.
Here is what i have tried:
Beta Was this translation helpful? Give feedback.
All reactions