To create a HTTP server with a specific route in TypeScript, we will use Express.js. Here's how you can do it:
npm init
and following the prompts.express
and @types/express
packages by running npm install express @types/express
.server.ts
and add the following code:index.ts274 chars13 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.
tsc server.ts
.node server.js
.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