create a http server and read the request body as json and return a json response in typescript

Here's an example of how to create an HTTP server in TypeScript, parse the request body as JSON, and return a JSON response:

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

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.headers['content-type'] === 'application/json') {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        const response = {
          message: 'Success!',
          data,
        };
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(response));
      } catch (error) {
        res.statusCode = 400;
        res.end(`Error: ${error.message}`);
      }
    });
  } else {
    res.statusCode = 404;
    res.end();
  }
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});
775 chars
32 lines

This code creates an HTTP server that listens on port 3000. When a POST request is made with the Content-Type header set to application/json, the request body is parsed as JSON and a response is returned with a message of "Success!" and the parsed JSON data. If the request body is not valid JSON, a 400 error response is returned. If the request method is not POST or the Content-Type header is not set to application/json, a 404 error response is returned.

gistlibby LogSnag