create a http server and read the request body as multipart form data in javascript

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.tsx
const http = require('http');
const formidable = require('formidable');

const server = http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: true });

    form.parse(req, (err, fields, files) => {
      if (err) {
        console.error(err);
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Internal server error');
        return;
      }

      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ fields, files }, null, 2));
    });

    return;
  }

  // handle other requests
  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('Not found');
});

server.listen(8080, () => {
  console.log('Server listening on http://localhost:8080 ...');
});
822 chars
31 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