Http Server in TypeScript

Our first program will demonstrate how to create a basic HTTP server. Here’s the full source code:

import * as http from 'http';

// A fundamental concept in HTTP servers is handlers. In TypeScript,
// we can create a handler as a function that takes a request and response object.
function hello(req: http.IncomingMessage, res: http.ServerResponse): void {
    // The response object is used to send the HTTP response.
    // Here our simple response is just "hello\n".
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('hello\n');
}

function headers(req: http.IncomingMessage, res: http.ServerResponse): void {
    // This handler does something a little more sophisticated by reading
    // all the HTTP request headers and echoing them into the response body.
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    for (const [name, value] of Object.entries(req.headers)) {
        res.write(`${name}: ${value}\n`);
    }
    res.end();
}

// Create the HTTP server
const server = http.createServer((req, res) => {
    // We register our handlers on server routes using a simple if-else structure.
    if (req.url === '/hello') {
        hello(req, res);
    } else if (req.url === '/headers') {
        headers(req, res);
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found\n');
    }
});

// Finally, we start the server listening on port 8090
server.listen(8090, () => {
    console.log('Server running on http://localhost:8090/');
});

To run the server:

$ ts-node http-server.ts
Server running on http://localhost:8090/

Access the /hello route:

$ curl localhost:8090/hello
hello

This example demonstrates how to create a basic HTTP server in TypeScript using the built-in http module. We define handler functions for different routes and use the createServer method to set up the server. The server listens on port 8090 and responds to requests on the /hello and /headers routes.

The hello function simply responds with “hello”, while the headers function echoes back all the request headers. This showcases how to access and manipulate request and response data in a TypeScript HTTP server.