JavaScript is disabled in your browser
Please enable JavaScript to use the site. For instructions select your browser:

How to Build a Simple Web Application Using Node.js?

 

Do you have an idea of a simple web application? But not sure, what to choose out of a variety of tools and technologies offered today?

We will explain, describe and show by a Node.js web application example how we would do it.

Let’s start from the very beginning:

 

WHAT IS MEANT BY SIMPLE APPLICATION?

The simple application implies that:

  • CRUD (create, read, update, delete) operations are employed without any complex logic of the endpoints;

Endpoint is URL (Uniform Resource Locator) simply put an address of the resource on the Internet. This address is used by the client to get access to the resource.

  • no roles are assigned;
  • no authentication system is used;
  • no language-extending libraries are applied (babel, typescript).

 

IS THIS THE TYPE OF THE APP YOU INTEND TO CREATE?

Then, our advice is as follows – use JavaScript. Node.js. Express.

 

WHY IS THAT JAVASCRIPT?

Let’s clear out together:

  • JavaScript was originally conceived as a simple language that could be used not only by programmers. The idea was a success: now we have the language, which can be easily used for both simple and complex products.
  • JavaScript is aimed to make the page dynamic. Animation, interactive buttons, and graphic elements: we can hardly imagine any app without these.
  • on the one hand, JavaScript  is a client-side language. Hence, in the case, the client is a browser that interprets the application code and executes it. The code interpreter is integrated into all popular browsers, meaning that no restrictions exist in terms of support.
  • on the other hand, thanks to Node.js platform (we will discuss it in details further on) JavaScript can be used as server-side language as well.

 

From this perspective, it is not surprising that JavaScript steadily holds the position of the most widely used programming language.

statistics

Source

 

According to the results of Stackoverflow survey, which covered more than 64,000 developers in 2017, JavaScript confidently leads the pack of the most frequently used programming languages (61.9%).

Note:

JavaScript has been holding the first place for five years on end, which does mean anything.

During all these years the language didn’t stand still, it evolved by leaps and bounds. New libraries and frameworks emerged, and the existing ones developed and expanded.

Angular, React, jQuery, Vue, Lodash – they are all talked and argued about, but, most importantly, they are successfully used and fulfill their intended purpose.

 

WHAT IS NODE.JS?

  • In fact, this is a programming environment, which provides conditions to use JavaScript as a server-side language. That is, the developers can use JavaScript both on the server side and on the client side, and they do not need to switch to specifics of another programming language, while the data format remains the same.

Each programmer has his/her own idea of the most appropriate language for the server side. In each case, accumulated experience, habits and features of the product being developed make all the difference.

  • According to the statistics related to a Node.js application for websites, the share of the platform use is steadily increasing:

 

statistics 1

Usage of Node.js for websites as of October 5, 2017, W3Techs.com

 

  • Using Node.js, you can build almost any web application, say, except for complex calculations. Although complex calculations can always be performed in another language, and then you can provide these data in JavaScript to use and manipulate them. But in this article, we are talking about the simple app.
  • Micro-service architecture can be referred to as a specific area of Node.js platform. In other words, Node.js is optimal for apps that consist of small modules (news feed, chat, store, etc.). While each module does not depend on others, and all together they form a single structure.
  • The additional advantage is that Node.js has a developed community around it. Thanks to this, there is easy-to-understand and use documentation and a lot of ready-made examples to employ, frameworks and libraries that allow to simplify and speed up the development.

 

You must admit that it is unreasonable to turn down any opportunities offered in the form of ready-made solutions and code manually from scratch. This is challenging, time-taking, and irrational. Moreover, we are talking about the simple app and not about anything complex or unique.

There are many step-by-step tutorials on Internet, describing in detail how to create Node.js web apps. Some of them are designed for skilled developers, but here we are offering a simple web application development option using Node.js for beginners and for those who are far from programming but interested in the logic of the process.

 

GETTING READY

To get started with creating the web application using Node.js, you should, at least, install Node.js.

The procedure is simple and does not take much time. Use one of the installation options found on Node.js official site.

A npm package manager is automatically installed along with Node.js.

Node.js uses a modular approach; this means you can expand the functions with a large number of modules. Their installation is the job for the package manager.

In our example, we will use MongoDB database management system (DBMS). Similarly to Node.js see the detailed documentation and installation manual on MongoDB official site.

 

To build a simple web application with Node.js, you will need the following modules:

  • framework for building an app skeleton (Express);
  • MongoDB driver;
  • web server restart tool (nodemon).

Note:

Due to this service program, the server will automatically restart with each code change.

 

EXPRESS

Why have we chosen this particular framework?

While being minimalistic and easy, Express provides all the functions a web app may need.

 

To create the app skeleton, you can use the Express app generator.

Click the link and you will see how simple it works.

The documentation describes the sequence of actions and commands and shows the results of their implementation.

 

The Express generator is one of the ways to create an app using Express.

How you will use it depends on the product specific features and the developer’s experience. On the one hand, it gives the developer some freedom of action. On the other hand, it provides flexibility, which is notably characteristic of Node.js, and often complicates the life of the developers, especially beginners.

No one will give you particular instructions as to what and how to do. Directory structure, number of files and plug-in external modules: the choice is yours.

 

Now let’s see as all above is implemented in practice.

 

EXAMPLE

  • Create a folder with a future project, and go into the folder and initialize the project answering the installer questions.

Use the following commands:

mkdir simple-api && cd simple-api && npm init

 

  • Then install the modules required:

npm i express mongodb body-parser

 

  • Install the automatic server restart tool, which facilitates significantly the development process:

npm i nodemon –save-dev

 

  • Having installed the required modules, create index.js file.

Here we connect all the required dependencies (third-party codes that your app will use).

 

  • Now indicate a listening port (digital indication of request receiver process) to make the server start listening to HTTP requests (requests to the server for some action from the client (browser) over HTTP.

// index.js
const express = require(‘express’);|
const app = express();
app.listen(3333, () => {
  console.log(‘server started!’);
});

 

  • Start the server with the following command:

nodemon index.js

 

  • Our server is started. Check its function and address it with the request from any browser.

For this purpose enter URL: http://localhost:3333.

 

The second possibility to check the server function: using Postman program.

Postman is a special program that makes it easier for the developers to create, test and monitor the API. With its help, you can send requests to the server and configure routes, as well as set request parameters and test function of the app.

 

postman 1

 

We have no registered endpoints, that is why the server returns now 404 status or HTML page with an error. But the main thing we cleared out is that the server has been started.

Now let’s come back to the types of HTTP requests: initially (when the protocol only appeared), the relationship between the client and the server implied only that the client wanted to get a resource (GET).

As the client-server relationship became more complex, a REST (REpresentational State Transfer) approach emerges. It enables the use of various HTTP methods for different actions: POST, GET, PUT, PATCH, DELETE.

Depending on the application purpose, set up the endpoint to fulfill the necessary requests.

 

  • Create the first endpoint in the app/ folder. The logic in this case is simple: we intend to address the server at /books and receive some definite answer:

// api/books.js
module.exports = function(app) {
  app.get(‘/books’, (req, res) => {
    res.send(‘Response’)
  });
};

 

  • Let’s suppose, we are not going to be limited to one endpoint in our app but want to use several of them (to create, read, update and delete data), then connect all handlers required to fulfill these actions in one file api/index.js:

// api/index.js
const apiBooks = require(‘./books’);
module.exports = function(app) {
  apiBooks(app);
 
// other routes
};

 

  • Having written the first endpoint, we register it and check:

// index.js
const express = require(‘express’);
const app = express();
// register endpoint
require(‘./api/index’)(app);
app.listen(3333, () => {
  console.log(‘server started!’);
});

 

4

 

  • Prior to starting with other endpoints, connect body-parser module (which will be in charge of requests handling) and specify the format of the endpoint input and output data – JSON:

// index.js
const express = require(‘express’);
const app = express();
// parse application/json
app.use(require(‘body-parser’).json());
// register endpoints
require(‘./api/index’)(app);
app.listen(3333, () => {
  console.log(‘server started!’);
});

 

  • Now establish the connection with “test” database using pre-installed mongodb driver. As the connection with the DB is established, send the database object as the second parameter to the registered routes:

// index.js
const express = require(‘express’);
const MongoClient    = require(‘mongodb’).MongoClient;
const app = express();
// parse application/json
app.use(require(‘body-parser’).json());
// register endpoints
require(‘./api/index’)(app, database);
MongoClient.connect(‘mongodb://localhost:27017/test’, (err, database) => {
  if (err) return console.log(err) 
  app.listen(3333, () => {
    console.log(‘server started!’);
  });
})

 

  • Then, we can write the endpoint for creating (CREATE) a new entry in DB. The entry includes fields: author, title, text.

The logic for creating this endpoint is also simple:

  • receive data in JSON format and form object book;
  • insert the object into books collection;
  • receive the result: either the error has occurred, or the document is created;
  • send the result to the user.

// api/books.js
module.exports = function(app, database) {
  …
  app.post(‘/books’, (req, res) => {
    const book = {
      author: req.body.author,
      title: req.body.title,
      text: req.body.text
    };
database.collection(‘books’).insert(book, (err, result) => {
       if (err) {
          res.send(err);
        } else {
          res.send(result.ops[0]);
        }
   });
  })
};

 

post 3

 

  • Create the endpoint to receive (READ) the entry from DB.

You can guess the logic on your own:

  • use id from request parameters and form the request;
  • send the request to DB;
  • handle the result: either the error has occured, or receive the document with data;
  • send the result to the user.

// api/books.js
module.exports = function(app, database) {
 …
 app.get(‘/books/:id’, (req, res) => {
   const ObjectID = require(‘mongodb’).ObjectID;
   const id = req.params.id;
   const query = { ‘_id’: new ObjectID(id) };
   database.collection(‘books’).findOne(query, (err, result) => {
     if (err) {
       res.send(err);
     } else {
       res.send(result);
     }
   });
 });
};

 

postman get

 

  • In a similar way create the endpoint  for updating (UPDATE) the entry in DB:
  • use id from request parameters and form the request;
  • receive data in JSON format and form the object book;
  • update the document in DB;
  • handle the result: either the error has occured, or receive the status of the operation;
  • send the result to the user.

// api/books.js
module.exports = function(app, database) {
 …
 app.put(‘/books/:id’, (req, res) => {
   const ObjectID = require(‘mongodb’).ObjectID;
   const id = req.params.id;
   const query = { ‘_id’: new ObjectID(id) };
   const body = {
     author: req.body.author,
     title: req.body.title,
     text: req.body.text
   };
   database.collection(‘books’).update(query, body, (err, result) => {
     if (err) {
       res.send(err);
     } else {
       res.send(result);
     }
   });
 });
};

 

postman put

 

  • And create the endpoint for deleting (DELETE) the entry:
  • use id from the request parameters and form the request;
  • delete the document from DB
  • handle the result: either the error has occurred, or receive the status of operation;
  • send the result to the user.

// api/books.js
module.exports = function(app, database) {
 …
 app.delete(‘/books/:id’, (req, res) => {
   const ObjectID = require(‘mongodb’).ObjectID;
   const id = req.params.id;
   const query = { ‘_id’: new ObjectID(id) };
   database.collection(‘books’).remove(query, (err, result) => {
     if (err) {
       res.send(err);
     } else {
       res.send(result);
     }
   });
 });
};


postman delete

 

We have told you how to create a simple Node.js web application. Using this application as a basis, you can expand its functionality with additional modules. But it depends on the purpose, for which you plan to use your future project.

 

Any questions left? Need any assistance with development? The earlier you contact Umbrella IT, the faster your ideas will come true to life.

 

Photo: Shutterstock.com


More

  • Umbrella IT Takes Top Spots in Web and App Development
    Umbrella IT Takes Top Spots in Web and App Development
    Skateboarders and bungee-jumpers love the risk of what they do. To them, the thrilling danger is fun and exciting–it keeps them alive. But when it comes to online presence, why take risks? Umbrella IT is the recognized safe option in Russia. We were the first official Symfony partner in Russia. Our pedigree is known to our …
  • How to Build an App like Uber: Development Guide to a Million Dollar Project
    How to Build an App like Uber: Development Guide to a Million Dollar Project
    Uber was the first company which successfully implemented both sharing economy and on-demand business model and boarded the entire world. The destabilization of the traditional taxi industry doesn’t prevent it from considering itself as a tech company, rather than a taxi firm. It makes sense: exemplary service and effective technical solutions are quite the things …
  • 6 Tips to Increase User Engagement with Mobile Apps
    6 Tips to Increase User Engagement with Mobile Apps
    What makes users come back to your app time and again? How to make your mobile app run at full blast and be indispensable to one and all? Do you have a dozen or maybe two dozens of apps installed on your smartphone, but actually use only a few of them? You don’t want your …