0

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));

1 Answer 1

-1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

in this case i get source.on('error', function() {}); ^ TypeError: source.on is not a function i tried to make JSON.stringify(new Blob([fs.readFileSync(file)])), but no way
holy .... i fix it... instead of use npm require('form-data'), i update nodeJS and FormData is available without dependices, and it works great, so much thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.