Express JS — Web Framework for NodeJS

Till now, we have seen how to structure front-end and popular framework for it. Now, Let’s start to make api, how will we manage database and to do all these, we need to dive into back-end.

NodeJS is web framework for event-driven programming and it is designed to build network applications.

Installation

NodeJS can be installed using two ways:
1. You can go the official website and download it according to your OS.
2. You can install it using command line by running following commands:

You can check whether it is installed or not by following:
node -v
Now, If you have noticed there’s one more thing which we have installed and that is npm.

NPM

Node Package Manager — It is a tool which has reusable components, set of publicly available libraries with version and dependency management.
You can check whether it is installed or not by following:
npm -v

Introduction:

Express js is a NodeJS web application server framework, designed for building single-page, multi-page, and Hybrid web applications.

Express adds dead simple routing and support for connect middleware, allowing many extensions and useful features such as following:

  • Modular middleware pattern
  • Async flow and Streams
  • Simple Routing

Project Initialisation ways

1. Express Generator

You can use application generator tool express-generator to create application structure. For that, you have to install express through command line.
npm install express-generator -g

It has different options to create particular application as follow:

--ejs for ejs engine support
--pug for pug engine support
--git to add .gitignore

express --view=pug node-demo
express --view=ejs node-demo

This will create application structure inside current directory named as node-demo and you can go to that directory and install required dependencies as

cd node-demo && npm install

Now, you can run the demo application by following command

Now, application will be running on http://localhost:3000/. You can start coding and run it. You can change/add routes, views, functions.
But here, server is getting started from bin/www. If you have noticed we have specified in second way that path to run the app. The reason behind it is server is getting created in that file.

Now, you can structure your code in MVC manner or whichever suits you.
(P.S : MVC is popular and best for it.)

2. Npm init

You can initialise the project by going into particular directory and do npm init command which will initiate the project. It’ll create package.json file inside current directory.

Which will ask you few questions regarding your project such as name, version, author, github url and etc.

Now, you can install dependencies or add in package.json and do npm install.

For express, run following command,

Now, Let’s make a file — you can name it as you like, I have made server.js and write code for starting the server.

This will start the server , using the port we defined and on route /about ,It will print the message. To run the application use following command.

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

P.S : I prefer nodemon in every project.
Now, you have successfully made one route, started the server and node application.

For real-time applications, there should be code structured in format and modulated.

Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method.

If you have noticed, in server.js we made one route of get and that has path, method and response specified.

Route Methods : Express supports all the methods from http such as GET, POST, DELETE, PUT, etc.

Route Parameters : Express also supports key parameters in URL which can be get through req.params.

Route Handlers : To handle request express provides handlers through which you can handle the callback functions. Route handlers can be in form of callback function, array of callback functions, and a combination of both.

A callback function will behave as middleware for handling request.
Also, you can create chain-able route handlers by using app.route() , where you can specify url at one location and make modular routes.

We have used express 4 and there is changes which we still need to implement for real-time applications.

Changes as per the official docs :
1. The built-in Express middleware functions express.favicon, express.logger, express.methodOverride, express.session, express.bodyParser and express.errorHandler are no longer available on the express object. You must install their alternatives manually and load them in the app.

2. You no longer need to load the app.router function. It is not a valid Express 4 app object, so remove the app.use(app.router); code.

3. Make sure that the middleware functions are loaded in the correct order — load errorHandler after loading the app routes.

Hence, we’ll need to change package.json &app.js

Let’s install necessary modules ,

Database Integration

You always need database to store data and manipulate that stored data. Express provides different node.js drivers for connect the database and add it to application.

Some of popular and supported database are MySQL, PostgreSQL, MongoDB, CouchDB, Redis and many more and each has it’s own driver to setup in application by installing it.

For MySQL, you need to install npm install mysql and make connection configurations.

Middleware

Middleware functions are functions which is executed once your request is fired and before sending response.

If you have scenario as in before signup, you need to check if the same email/user exists or not, or in some scenario, before sending response for security purpose check authentication/token.
This is where middleware is useful and can call the middleware function in main fille using app.use()

Before serving any route, this will be called and will give error of 404 with Not found. Notice there’s next() function which will move to next calls, functions, code to execute.
You can check this middleware function with wrong api url.

One of top feature of Express is you can create MVC architecture on the server side using Express and create single page, multi-page, and hybrid web applications.

There isn’t any particular structure to follow for Express, you can create MVC using folder structure as follow :

Where you can write business login in controller, and your model/schema will be in model under api directory.
Config will contain configuration files such as database info, error messages, constants for server.
Routes will contain route files as per module for better understanding and reliability.
Views will have files for templates.
.env will have General settings, and variable stored to use in server file.

I’d appreciate suggestions/feedback.
Thank you for reading and If you learnt something, Clap :)

Passionate about places, photos and coding! Food is love !!