create a http server with a get route in typescript

Here's an example of how to create a simple HTTP server with a GET route in TypeScript using the Node.js http module:

index.ts
import * as http from "http";

const hostname = "localhost";
const port = 3000;

const server = http.createServer((req, res) => {
  if (req.method === "GET" && req.url === "/") {
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/plain");
    res.end("Hello, World!\n");
  } else {
    res.statusCode = 404;
    res.end();
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
453 chars
20 lines

In this example, we create an HTTP server using the http.createServer() method, which takes a callback function as an argument. The callback function receives the request and response objects as parameters, and we can use these objects to handle incoming requests and generate appropriate responses.

We define a GET route for the root path ("/"), which responds with a plain text message "Hello, World!\n". If the requested route does not match any of our defined routes, we return a 404 status code with an empty response.

We start the server by calling the server.listen() method and passing in the desired port and hostname. Once the server is listening, we log a message to the console to indicate that the server is ready.

gistlibby LogSnag