I try to post via node-fetch to golang API files with some structure, I can make it from postman, but no way from NodeJS
Hi there. im at dead end, i had tried everything...
I need make a request to golang api, i can create it in Postman: its look like this: postman request
And I need to repeat it in NodeJs, But i always getted bad request from API
here is my code on Node
let formData = new FormData()
formData.append('postUUID', postUuid)
json.data.uploadIds.map((upl, index) => {
let file = data.files.find(el => el == upl.filename)
formData.append(upl.uuid, fs.readFileSync(file));
})
let headers = new Headers()
headers.append('Authorization', 'Bearer '+token)
headers.append("Accept", "application/json");
fetch(API+'/posts/uploadMediaFiles', {
method: 'POST',
headers,
body: formData
})
Difference with postman generated code only in formdata.append("f2b07a43-f79f-4033-ab2d-bb3176934679", fileInput.files[0], "/file_0.jpg");
and i do instead of formData.append(upl.uuid, fs.readFileSync(file));
fs.readFileSync()
returns either a string
or a Buffer
containing only the contents of the file itself. This means you're passing only the raw contents of the file to FormData.append()
, which in turn means your call to fetch
will treat the resulting key/value pair not as a file - this only happens when passing a value
with a Blob
or File
type (MDN).
Instead, cast the contents of the read file as an Array
to a new Blob
object, then pass both the blob object and the name of the file you want to the FormData
field (a quick tip of the cap to the answer on this SO question):
formData.append(upl.uuid, new Blob([fs.readFileSync(file)]), upl.filename);