Http Server in JavaScript

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

const http = require('http');

// A fundamental concept in HTTP servers is handlers. In Node.js,
// we create handler functions that take a request and response object.

function hello(req, res) {
    // The response object is used to send the HTTP response.
    // Here our simple response is just "hello\n".
    res.end('hello\n');
}

function headers(req, res) {
    // This handler does something a little more sophisticated
    // by reading all the HTTP request headers and echoing them
    // into the response body.
    let responseText = '';
    for (const [name, value] of Object.entries(req.headers)) {
        responseText += `${name}: ${value}\n`;
    }
    res.end(responseText);
}

// We create our server and define the routes
const server = http.createServer((req, res) => {
    if (req.url === '/hello') {
        hello(req, res);
    } else if (req.url === '/headers') {
        headers(req, res);
    } else {
        res.statusCode = 404;
        res.end('Not Found');
    }
});

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

To run the server:

$ node http-server.js
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 Node.js. We use the built-in http module to create the server and define routes.

In Node.js, we define handler functions that take a request and response object. These are similar to the concept of handlers in other web frameworks.

We set up two routes: /hello which returns a simple greeting, and /headers which echoes back all the request headers.

The createServer method is used to create the HTTP server, and we define a callback function that handles all incoming requests. Inside this function, we check the URL of the request and call the appropriate handler.

Finally, we call server.listen to start the server on port 8090.

This setup provides a simple and flexible way to create HTTP servers in Node.js, allowing you to easily define different routes and their corresponding behaviors.