create a http server with a specific route and a specific status code in typescript

To create an HTTP server with a specific route and a specific status code in TypeScript, we can use the popular Node.js web framework, Express. Here's an example code snippet that demonstrates how to define a specific route and return a specific status code:

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

const app = express();

// Define the route /hello
app.get('/hello', (req: Request, res: Response) => {
  // Return a 200 status code with the message "Hello, World!"
  res.status(200).send('Hello, World!');
});

// Define the route /healthcheck
app.get('/healthcheck', (req: Request, res: Response) => {
  // Return a 204 status code with no message
  res.status(204).send();
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});
532 chars
21 lines

In this example code, we use the get method of the app instance to define two specific routes - /hello and /healthcheck. When a request is made to these routes, the associated callback function is executed, and we return a specific status code with a message (in the case of /hello) or without a message (in the case of /healthcheck). We use the status method to set the appropriate HTTP status code, and the send method to send a response to the client. Finally, we start the server by calling the listen method of the app instance, and listen on port 3000.

This is just a basic example, and there are many more advanced features in Express that you can use to build powerful web applications.

gistlibby LogSnag