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

To create an HTTP server in TypeScript, we can use the built-in http module. Here's an example of how to create a server and read the request body as form data:

index.ts
import * as http from 'http';

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    
    req.on('data', chunk => {
      body += chunk.toString();
    });

    req.on('end', () => {
      const formData = new URLSearchParams(body);
      console.log(formData.get('foo')); // prints the value of the 'foo' field
    });
  }

  res.end('Hello World!');
});

server.listen(8080, () => {
  console.log('Server listening on port 8080');
});
486 chars
23 lines

In this example, we create an HTTP server using http.createServer(). In the callback function, we check if the request method is POST. If it is, we create an empty string variable called body, and then set up two event listeners: one for 'data' and one for 'end'.

The 'data' event is emitted whenever a chunk of data is received in the request body. We append each chunk to the body variable as a string. The 'end' event is emitted when all the data has been received. At this point, we create a new URLSearchParams object using the body string. This object allows us to easily access the form data by field name.

Finally, we output the value of the 'foo' field to the console, just as an example. Normally, you would do something more useful with the form data, such as save it to a database or use it to generate a response.

We then end the response with 'Hello World!' and start the server listening on port 8080.

gistlibby LogSnag