create a http server and read the request body in typescript

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

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

const server = http.createServer((request, response) => {
  if (request.method === 'POST') {
    let body: string = '';
    request.on('data', (chunk) => {
      body += chunk.toString();
    });
    request.on('end', () => {
      try {
        const data = JSON.parse(body);
        // Do something with the parsed data
        response.writeHead(200, { 'Content-Type': 'application/json' });
        response.write(JSON.stringify({ message: 'Request body parsed successfully.' }));
        response.end();
      } catch (error) {
        console.error(`Error parsing request body: ${error}`);
        response.writeHead(400, { 'Content-Type': 'text/plain' });
        response.write('Error parsing request body.');
        response.end();
      }
    });
  } else {
    response.writeHead(405, { 'Content-Type': 'text/plain' });
    response.write('Method not allowed.');
    response.end();
  }
});

const port = 3000;

server.listen(port, () => {
  console.log(`Server running on port ${port}.`);
});
1037 chars
35 lines

In this example, we create an HTTP server using the createServer method from the http module. We handle POST requests by listening to the data and end events of the request object. The request body is stored in the body variable and parsed as JSON using the JSON.parse method. If an error occurs during parsing, a 400 Bad Request response is sent. If parsing is successful, a 200 OK response is sent with a JSON message.

For all other HTTP methods, a 405 Method Not Allowed response is sent.

Note that this example only parses JSON request bodies. For other types of request bodies, you may need to use a different parsing method.

gistlibby LogSnag