In this article we will show how we can build a simple Node.js HTTP server from a beginner’s perspective. Node is a fantastic candidate for creating web servers; which are lightweight and can deal with a great number of simultaneous requests. This means this is a great beginner’s guide if you’re going to build scalable web applications.
We can use the several core modules shipped with Node.js to set up our own http server. With http module’s simple but powerful api, it is simple to create an http server. Let’s begin by making an empty file named myFirstHTTPServer.js and write the following code into it:
//Lets require/import the HTTP module
var http = require(‘http’);
//Lets define a port we want to listen to
const PORT=8080;
//We need a function which handles requests and send response
function handleRequest(request, response){ response.end(‘It Works!! Path Hit: ‘ + request.url); }
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server server.listen(PORT, function(){ //Callback triggered when server is successfully listening. Hurray! console.log(“Server listening on: http://localhost:%s”, PORT); });
Now to see Node’s magic simply start the server by running the file. Follow the below command to run your program in the terminal:
> node myFirstHTTPServer.js
#output
Server listening on: http://localhost:8080
On your browser, open up the url http://localhost:8080 and it should serve you the text returned from our program. Play with the path of the URL and see the message displayed.
Analysis of The Above Program
Now lets break the above program into sub blocks and see what’s happening:
Loading the http Module
Node.js has core modules to create http/https servers, hence we have to import the http module in order to create an HTTP Server.
//Lets require/import the HTTP module
var http = require(‘http’);
Defining the Handler Function
A function which will handle all requests and reply accordingly is needed. This is the point of entry for your server application, you can reply to requests as per your business logic.
//We need a function which handles requests and send responsefunction handleRequest(request, response){ response.end(‘It Works!! Path Hit: ‘ + request.url); }
Creating and Starting the Server
Here we are creating a new HTTP Server Object and then asking it to listen on a port. The createServer method is used to create a new server instance and it takes our handler function as the argument. Then we call listen on the server object in order to start it.
//Create a servervar server = http.createServer(handleRequest);
//Lets start our server server.listen(PORT, function(){ //Callback triggered when server is successfully listening. Hurray! console.log(“Server listening on: http://localhost:%s”, PORT); });
Adding in a Dispatcher
Now that we have a basic HTTP Server running, it’s time we implement some real functionality. Your server should respond differently to different URL paths. This means we need a dispatcher. Dispatcher is kind of router which helps in calling the desired request handler code for each particular URL path. Now lets add a dispatcher to our program. First we will install a dispatcher module, in our case httpdispatcher. There are many modules available but lets install a basic one for demo purposes:
> npm install httpdispatcher
If you’re unaware npm is a package manager which provides a central repository for custom open sourced modules for Node.js and JavaScript. npm makes it simple to manage modules, their versions and distribution. We used the `npm install` command to install the required module in our project.
Now we will require the dispatcher in our program, add the following line on the top:
var dispatcher = require(‘httpdispatcher’);
Now let’s use our dispatcher in our handleRequest function:
//Lets use our dispatcherfunction handleRequest(request, response){ try { //log the request on console console.log(request.url); //Disptach dispatcher.dispatch(request, response); } catch(err) { console.log(err); } }
Let’s define some routes. Routes define what should happen when a specific URL is requested through the browser (such as /about or /contact).
//For all your static (js/css/images/etc.) set the directory name (relative path). dispatcher.setStatic(‘resources’);
//A sample GET request dispatcher.onGet(“/page1”, function(req, res) { res.writeHead(200, {‘Content-Type’: ‘text/plain’}); res.end(‘Page One’); });
//A sample POST request dispatcher.onPost(“/post1”, function(req, res) { res.writeHead(200, {‘Content-Type’: ‘text/plain’}); res.end(‘Got Post Data’); });
Now lets run the above program and try the following URL paths:
GET /page1 => ‘Page One’
POST /page2 => ‘Page Two’
GET /page3 => 404
GET /resources/images-that-exists.png => Image resource
GET /resources/images-that-does-not-exists.png => 404
You can use your browser to do a GET request just by entering the URL in the address bar. For a POST request you can use a tool like Postman.
All Done! Now you have a small simple HTTP server up and running.
In this blog we covered creating a basic HTTP server using the http module along with some introduction to npm and use of a simple dispatcher module (httpdispatcher) to dispatch http requests to appropriate routes. There you have it folks, it’s as simple as that. In a production enviorenment we’d advise using something like express. You can learn more on this article