Learn the basics of NodeJs and Express by creating a basic elections app

Uddhav Navneeth
Code To Express
Published in
9 min readMay 13, 2019

This article is to illustrate how to create a basic app in Node.js using express and hbs (as the view engine). We will be creating a very simple and basic elections app, which will run on your local host. On running it you can choose from one of the 3 candidates provided and it shows you the current results on it.

I strongly believe that a language or a framework should be learnt from the basics and this is not the ideal method for you to learn node.js and express from scratch. But this will be helpful for people who want to get a feel of node.js and express, or people who are a little confused about the functioning of it.

The next part about the basics of Nodejs and Express can be skipped if you already know about it.

What is Nodejs?

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.

In simple terms, Javascript was a language which originally ran only on browsers, now nodejs extended its functionality and allows us to run it on our computers. It is largely used to create servers (backend) for web pages or mobile applications. V8 engine is what converts the javascript language to machine code. To get a more in depth understanding on Javascript and why it is so beautiful I would recommend giving this article a read: https://medium.freecodecamp.org/what-exactly-is-node-js-ae36e97449f5

What is Express?

Fast, unopinionated, minimalist web framework for Node.js

This how express describes itself on its website. It can be imagined as a thin layer on top of node.js which provides it with more ease and structure. It allows us to create servers, web apps and manage routes with a lot of ease. It has a MVC (model view controller) like structure and is super fast.

Getting to the Actual App

Firstly download Node.js from the official website: https://nodejs.org/en/

I would recommend the readers to use a text editor like (VS code) Visual Studio Code, Atom or an IDE like Webstorm. I personally prefer Visual studio code and will be using it, especially because it has an integrated terminal in it, which is very useful as nodejs needs to be run from a terminal.

Firstly create a folder for the project and name it whatever you like, I’m calling it Basic-Elections-Node-App. Open this folder using vs code or any editor you like and using the terminal (for people using integrated terminal you will already be at the folder directory) reach this folder directory. ctrl+` can be used to open the integrated terminal in vs code. In the directory create a folder named ‘views’ (The naming for this needs to be exact). Inside the views folder you will have your front end web pages. In this case you can download the front end from the github repo. In the main folder directory create a file named ‘server.js’ (this can be named anything but needs to end with a ‘.js’). Now go to the terminal and run ‘npm install express’, then after it finishes downloading, run ‘npm install hbs’ and ‘npm install body-parser’. After running these commands 2 more files will automatically be created ‘package-lock.json’ and ‘node_modules’. Package-lock.json gives a brief model of the packages installed and node_modules has all the modules in the application. Node_modules is actually a very heavy file so we don’t tend to push it or send it that is why we create .gitignore file in which we write ‘node_modules’. This can be skipped if you intend to run it only on your local setup and are not planning to push the code to a version control system like Github or GitLab. Now the file directory should look something like this:

NPM stands for node package manager. It has thousands of free packages which can be downloaded and used with javascript. A package in Node.js contains all the files you need for a module. Modules are JavaScript libraries you can include in your project.

So we have installed the express package. This is required for us to use express. We have also installed hbs. Hbs stands for handlebars, it is a templating engine. It is used to serve front end web pages. There are other options which can be used as templating engine like ejs, pug, jade, etc. Body-parser is a package which is used too. It can be explained as it extracts the entire body portion of an incoming request stream and exposes it on req.body. It was a part of Express.js earlier but now you have to install it separately. This body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request. This will make more sense through the election app.

Your server.js file is going to be the main file which sets up a server and executes your logic. You can download the whole code for this project from the github repo given at the end. Let us start writing the code for server.js:

line 1,2 and 4 tell the compiler/engine that we are going to be using the packages mentioned. The left hand name after const is what we are going to use it as and the name inside require is the package’s original name.

In line 6 we create a new express application.

In line 7 we assign a variable ‘port’ value 3000. This is later going to be used(line 12) to start a new HTTP server on port 3000.

Line 9 is used to tell express application that we are going to be using hbs as the templating engine.

Line 10 is the middleware to handle url encoded data. URL encoded data is a form of encoding data which is used in HTTP requests. BodyParser helps in translating/decoding the url encoded data.

As mentioned before in line 12 a new HTTP server is started on port variable (which is 3000 in our case).

Line 13 is used for us to know that the server is up and running on our terminal. Run this by typing ‘node server.js’ in the terminal and hitting enter . The terminal should look like this:

The server is up on port 3000 but we have not configured anything for it currently so we won’t be able to see anything. The live server can be closed by clicking ctrl+c . Let us write the rest of the code for this application. Firstly we would have to write 2 html/hbs pages in our views folder, which will be rendered by our server. The first one being ‘elections.hbs’ as follows (the code can directly be copied from the github repo mentioned at the end).

This is a basic HTML page which creates a radio button form. As we have chosen a form action method, on submitting this form the value of the chosen radio button is sent to /send POST route which we will configure in server.js file.

The name attribute is same for all three radio buttons so that the client can only select one at a time and on submitting, the value defined for an input gets passed.

The second html/hbs page would be the result page. This is where you will display the results.

In this what we are doing is actually displaying the current score of each person by showing the value of the variables uddhav, mukund, and ujjwal. These variables have been passed to the page from the server.js file. In hbs {{}} are written to use a variable, hence the name handlebars as they kind of look like handlebars. In line 14 we give the client (person interacting with the application) option to go back and vote again.

So the overall file directory structure of the application should now look like this:

Let us complete our server.js file:

We initialize three variables mukundh uddhav and ujjwal to zero.

Then on line 17 we use the GET method of HTTP protocol to render the elections.hbs page when http://localhost:3000/ is entered as the url. So once you run ‘node server.js’ and go to the browser and http://localhost:3000/ in the address bar you will get this:

req and res in line 17 stand for request and response. These are how HTTP protocols work. Based on the method used response is what the server is instructed to do while request is related to what the client asks the server to do. In our case the server renders the election page for the route ‘/’. Close the server and let us write the next part of server.js:

We are creating a POST route on ‘/send’ so that when a POST method is used on this route then the request from the client which is submitting the form is parsed by the body parser and the result is displayed on our console/terminal. So run ‘node server.js’ in the terminal and go to your browser and enter http://localhost:3000/ select any one of the candidates and submit the form. On your terminal you will see what is there in req.body :

Close the server and let us write the final part of server.js where we use the information we get from req.body.

Here we remove the console.log(req.body) and instead write our logic. This is a simple if-else structure in which if the candidate has a specific value then the respective variable is incremented.

In line 32, like we did in our GET method, we are rendering another page, this time we are rendering result.hbs, but after that we are passing the variables uddhav , mukundh and ujjwal to be used in the result.hbs template. This is actually a short way of writing this using ES6 structure, otherwise it could have also been written as:

res.render('result.hbs', {uddhav: uddhav, mukundh: mukundh, ujjwal: ujjwal});

where the left value is the name of the variable which you want to use in the result.hbs template and the right value is the variable from server.js. These left variable names are used in result.hbs using {{}} like {{uddhav}} . Now the basic elections node app is complete. If you were to run ‘node server.js’ in the terminal and then open the browser at http://localhost:3000/ you will be able to use the app.

You can play around with the applications code to learn new things about how the framework functions.

Well Hope This Helped You in Some Form or Another !!

You can download the app from here and further develop it or run it as instructed in this article.

--

--