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

Here's an example of creating an HTTP server in TypeScript and then reading the request body as text:

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

const server = http.createServer((req, res) => {
  let body = '';
  req.on('data', (chunk) => {
    body += chunk.toString();
  });
  req.on('end', () => {
    console.log(body);
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, world!');
  });
});

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});
418 chars
19 lines

In this example, we create an HTTP server using the http module and listen on port 3000. When a request is received, we create an empty string (body) to store the request body. We then listen for the data event on the request object, which is emitted whenever a chunk of data is received from the client. We append each chunk of data to the body variable. When the end event is emitted, we know that the entire request has been received, and we can then process the request and send a response back to the client. In this case, we simply log the request body to the console, set the response status code and headers, and send back a simple text response.

gistlibby LogSnag