NodeJs Http Server (Web Server)

Making a simple HTTP server in Node.js is very simple. Node.js provides extremely easy-to-use HTTP APIs, a simple web server.

Let’s take a look at a very simple example:

const http = require('http');

const http_port = 8000;

// Instantiate the HTTP server.
const httpServer = http.createServer((req, res) => {
    if (req.method == 'POST') {
        var jsonString = '';

        req.on('data', function (data) {
    	    try {
                console.log(data.toString());
    	    }
    	    catch(err) {
    		console.log(err);
    	    }
        });

      	req.on('error', (err) => {
            // This prints the error message and stack trace to `stderr`.
            console.log("POST ERROR \n" + err.stack);
      	});

        req.on('end', function () {
             console.log('POST Request ended here.');
        });
    }
    
    res.writeHead(200);
    res.end();
    console.log('Response ended here. \n ');
});


httpServer.listen(http_port, () => {
  console.log("Web server is listening on port %s \n", http_port);
});

Save this in a file called server.js – run node server.js, and your programĀ  will hang there… it’s waiting for connections to respond to, so you’ll have to give it one if you want to see it do anything. If everything has been set up correctly, you should see your server’s request & response log.

Let’s take a more in-depth look at what the above code is doing. Function in http.createServer takes a request object and a response object as parameters.

The request object contains things such as the requested URL, Request Method and data.

The response object is how we send the headers and contents of the response back to the user making the request. Here we return a 200 response code (signaling a successful response) with empty body. Other headers, such as Content-type, would also be set here.

The listen method, which causes the server to wait for incoming requests on the specified port – 8000, in this case.

There you have it – your most basic Node.js HTTP server.

Leave a Reply