Node.js – How to create a HTTP server

By | 02/10/2019

In this post, we will see hot to create a HTTP server using Node.js.
Node.js has a module called HTTP, which allows to transfer data using HTTP.
With this module we can create an HTTP server that listens to server ports and gives a response back to the client.

We open Visual Studio Code, create a new file called serverweb.js and we write this code:

// import the module http
var http = require('http');

// creation of the Server
var serverweb = http.createServer(function(request, response){
    // definition of the status code to send at the header
    var codhead= 200;
    // definition of the output message
    var message = "The call was done from ";
    // with request.url it is possible to know the part of the url after domain 
    switch (request.url)
    {
        case "/api":
                message = message + "API";
                break;
        case "/test":
                message = message + "TEST";
                break;
        case "/":
                message = message + "ROOT";
                break;
        default:
                message = "This position isn't known";
                codhead = 404;
                break;
    }
    // it sends a status code and information to the client
    response.writeHead(codhead, {"Content-Type": "text/html"});
    // text shown in the page 
    response.write("<b>" + message + "</b>");
    response.end();
}).listen(3366, '127.0.0.1');     // the server will listen on the port 3366

console.log("server started")



Now, in order to verify our application, we run it, open a browser and we go to localhost:3366:

ROOT

API

TEST

OTHER URL



Leave a Reply

Your email address will not be published.