create a http server with a post route in typescript

Here's an example of how to create an HTTP server with a POST route using TypeScript and the Express library:

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

const app = express();
app.use(express.json());

app.post('/api/users', (req: Request, res: Response) => {
  const { username, email } = req.body;
  // do something with the data received from the client
  res.status(201).send(`User ${username} created with email ${email}`);
});

const port = 3000;
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
445 chars
16 lines

In this code, we import the express library and create an instance of the express application. We also enable the parsing of JSON data from the request body using express.json().

Then, we define a POST route at /api/users. When a POST request is received at this endpoint, the code inside the callback function is executed. We extract the username and email properties from the request body using req.body, and then we can process this data as needed.

Finally, we start the server listening at a certain port, and log a message when the server is ready to accept requests.

This example creates a simple REST API for users using a POST request to create new users. You can adapt this code to create other routes with different HTTP methods as needed.

gistlibby LogSnag