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

Here is a simple example of how to create an HTTP server in Node.js using TypeScript and Express, and read the request body as JSON:

index.ts
import express, { Request, Response } from 'express';

const app = express();
const port = 3000;

// Middleware to parse the request body as JSON
app.use(express.json());

app.post('/api/data', (req: Request, res: Response) => {
  const data = req.body;
  console.log(data);
  res.send('Data received');
});

app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}`);
});
401 chars
18 lines

In this example, we use the Express framework to create an HTTP server. We then specify a route for handling POST requests to /api/data.

We use the middleware express.json() to parse the request body as JSON. The parsed JSON data is then available in req.body. We log the data to the console and send a response back to the client with res.send().

Finally, we start the server by calling app.listen() and passing in the desired port number.

Note that this example assumes that you have installed the required dependencies via npm install express http @types/express @types/node.

gistlibby LogSnag