To create an HTTP server in node.js, we can use the built-in http module. To read request body as multipart form data, we need to use a third-party module called "formidable".
Here is an example code snippet to create a HTTP server and read request body as multipart form data in JavaScript:
index.tsx822 chars31 lines
In the above code, we create a server instance using http.createServer()
method. We listen to incoming requests on port 8080.
When receiving a POST request to '/upload', we initialize a new instance of formidable
module with multiples
option set to true
. This is because, when a form submission contains multiple files, formidable by default saves them into a temporary file on disk.
We then parse the request body using form.parse()
method, which invokes a callback function with three arguments: err
, fields
, and files
. If there is an error during the parsing, we return a 500 Internal Server Error response. Otherwise, we return the parsed fields and files as a JSON response.
For all other requests, we return a 404 Not Found response.
Note: This code example requires "formidable" module to be installed via npm.
gistlibby LogSnag