Node.js - Create web server using http module

Node.js

In this tutorial we will learn to create a simple Node.js web server and handle HTTP requests using http module.

Node.js provides capabilities to create web server that can handle HTTP request asynchronously.

Create a simple server

To create a simple Node.js web server we need the http module. It is the core Node module and hence we don't have to install it using NPM. So, lets create a web server.

NPM is a Node Package Manager. It helps in installing packages in our projects.

In the following example we are creating a web server. We first import the http module that helps us to create the server.

Next, we create a server using the createServer() method. It takes a callback function that takes two parameters request and response.

Finally, we make the created web server to listen to port 9000 for incoming requests.

Here is the code.

const http = require('http');

const PORT = 9000;

const server = http.createServer(function(request, response) {
    // some code goes here...
});

server.listen(PORT);

console.log(`Server started and listening at port ${PORT}.`);

To start the server we go ahead and run the following command in the terminal. Note! I have saved the code in a file by the name http-web-server.js. Change it as per your filename.

$ node src/http-web-server.js
Server started and listening at port 9000.

When we run the above command then our Node web server will start listening at port 9000. Note! The execution will not stop. To stop the server we have to hit Ctrl + C key.

Now, open a web brower like Firefox, Chrome, Edge and visit http://localhost:9000 url. At the moment we will not see any result as we have not yet set anything to handle the HTTP request. So, lets do that in the next section.

Handle HTTP request

In the following section we will learn to handle HTTP request when we open http://localhost:9000 url.

The callback function that we saw above when we created the server has two parameters namely, request and response.

The request object has url property and it holds the requested url. So, we will use it.

The response object has writeHead method which helps in setting the header. Then we have the write method that helps to write the response body. And there is end method which helps in sending the response.

Lets say, we want to print out the message Hello, World! when we visit the home page at http://localhost:9000. As, it is the home page so we have to check for /.

const http = require('http');

const PORT = 9000;

const server = http.createServer(function(request, response) {

    // we are setting the header
    const header = {
        'Content-Type': 'text/html'
    };

    // checking for home page url /
    if (request.url === '/') {
        response.writeHead(200, header);
        response.write('Hello, World!');
    }

    // if requested url is not known then prompt error response
    else {
        response.writeHead(400, header);
        response.write('Bad request!');
    }
    
    response.end();
});

server.listen(PORT);

console.log(`Server started and listening at port ${PORT}...`);

HTTP code 200 means OK and 400 means Bad request.

Now, stop the running server in the terminal by hitting Ctrl + C and re-run it. Now, visit the home page http://localhost:9000 url. This time we will see the message Hello, World!.

This happens because the if condition is satisfied and if-block is executed.

Now, if we visit something like http://localhost:9000/some-unknown-page then we will get Bad request! message.

This happens because we are not handling the /some-unknown-page and hence the else-block is executed which gives the Bad request! message as response.

HTTP verb

By default, when we visit the above url http://localhost:9000 the HTTP request has the GET verb. We can handle other HTTP verbs like PUT, POST etc. using the method properties of the request object.

In the following example we will modify the above example to handle HTTP verb GET for the / request.

const http = require('http');

const PORT = 9000;

const server = http.createServer(function(request, response) {
    // setting the header to json
    const header = {
        'Content-Type': 'application/json'
    };

    // handling the home url /
    if (request.url === '/') {

        // checking the HTTP verb
        switch (request.method) {

            // if GET verb used
            case 'GET':
                response.writeHead(200, header);
                response.write(JSON.stringify({ message: 'Hello, World!' }));
                break;

            // if unknown verb used then give out bad request message
            default:
                response.writeHead(400, header);
                response.write(JSON.stringify({ message: 'Bad request!' }));
        }
    }
    
    // when unknown page is requested then give out bad request message
    else {
        response.writeHead(400, header);
        response.write(JSON.stringify({ message: 'Bad request!' }));
    }

    response.end();
});

server.listen(PORT);

console.log(`Server started and listening at port ${PORT}...`);

Now, lets re-run the server and this time lets open Postman app and visit the http://localhost:9000 url.

This time we will get the response as JSON.

postman nodejs http server json api

If we try to visit some other url like http://localhost:9000/some-unknown-page then it will give error.

postman nodejs http server json api

Alright, it is time for you to practice what you have learned. Thanks for reading. Please share this tutorial. See you in the next tutorial. Have fun.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT