create a http server and add a custom header to the response in typescript

To create a simple HTTP server in TypeScript, we can use the built-in http module of Node.js. Here's an example:

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

const port = 3000;

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain', 'Custom-Header': 'Hello World' });
  res.end('Hello, World!\n');
});

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

In this example, we import the http module and define the port on which our server will listen. We create the server using the http.createServer() method and pass a callback function that will be executed for every incoming request.

In the callback function, we use the res.writeHead() method to set the response status code and headers. Here, we have added a custom header called Custom-Header with a value of Hello World. We then send the response using the res.end() method.

Finally, we start the server by calling its listen() method and passing the port number and a callback function that will be executed when the server starts listening.

By using res.writeHead() to set a custom header, we can send additional information with the response. This can be useful in cases where we need to provide extra metadata, such as authentication tokens or custom session IDs, with the response.

gistlibby LogSnag