I have seen almost all answers in relation to this suggest to use some variant of FormData within nodejs to build a multipart form.
I wish to achieve the same without using the FormData library, but instead just using request headers and a string for the request body.
Only one answer hints at how this can be achieved, but the solution uses a stringify function on the string payload so I am not sure how the correct stringified body should look like.
Regardless, I have gotten this far;
import { RequestOptions } from "http"
const path: 'url/'
const method: 'POST'
const body = `--BOUNDARY
\nContent-Disposition: form-data; name="file"; filename="test.txt"
\nContent-Type: text/plain
\nThis is the content of the file
\n--BOUNDARY
\nContent-Disposition: form-data; name="form-field-one"
\nexample1
\n--BOUNDARY
\nContent-Disposition: form-data; name="form-field-two"
\nexample2
\n--BOUNDARY--`
const headers = {
'content-type': 'multipart/form-data; boundary=BOUNDARY',
'content-length': String(Buffer.byteLength(body))
}
const options = {
path,
method,
headers,
body
}
const response = await execute(options)
I cannot create a fully minimal reproduction as I am not permitted to post the execute function contents, but I can describe the function signature I need to use (which is why I need to use this string approach).
For what its worth, i think the function is simply using the basic builtin nodejs http library.
import { RequestOptions } from "http"
const execute = async (options: RequestOptions): Promise<any> => { ... }
I get an error using this, but the error is not helpful at all due to the internals of the function.
Regardless, I believe it should be possible to replicate sending a multi-part form (with file and form fields) using just the body and headers of a POST request without an additional library to transform the data of the body.
My string is a modified output from a successful Postman request multipart form request.
Can someone point out what I am doing incorrectly?