create a http server with a specific route in typescript

To create a HTTP server with a specific route in TypeScript, we will use Express.js. Here's how you can do it:

  1. First, make sure you have Node.js installed on your computer.
  2. Create a new directory for your project and open it in your terminal or command prompt.
  3. Initiate a new Node.js project by running npm init and following the prompts.
  4. Install express and @types/express packages by running npm install express @types/express.
  5. Create a new file called server.ts and add the following code:
import express, { Request, Response } from 'express';

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

app.get('/hello', (req: Request, res: Response) => {
  res.send('Hello World!');

app.listen(port, () => {
  console.log(`Server started at http://localhost:${port}`);
274 chars
13 lines

In this example, we imported the express package and defined our app instance with const. Then, we set the port number to 3000.

Next, we added a route definition using the app.get method. This route listens for GET requests with path /hello. When a request is made, it will send a response back with the message "Hello World!".

Finally, we started our server by calling the app.listen method and passing in the port number. We also added a console log message to verify that our server started successfully.

  1. Compile your TypeScript file by running tsc server.ts.
  2. Start the server by running node server.js.
  3. Visit http://localhost:3000/hello in your web browser to test if the /hello route can be accessed.

That's it! You've successfully created an HTTP server with a specific route using TypeScript and Express.js.

gistlibby LogSnag