Express.js Tutorial

Introduction to Express.js

This tutorial will help you to learn basic and advance the concept of Express.js. Express.js is a web framework for Node.js. It is fast, robust and asynchronous. It is a flexible and minimal Node.js web application framework. It provides various features for mobile and web applications.

What is Express.js?

Express.js is a web application server of Node.js framework. It is designed for building dynamic web applications. It is the back end part of the MEAN stack package. The MEAN is an open-source JavaScript software stack. It is free adlicensed under MIT. It is launched in 2010 by TJ Holowaychuk

Why use Express.js?

With Express.js you will be able to build APIs in JavaScript. You can create, retrieve, update, and delete functionality. It is a powerful tool for web app back-end or new back-end framework. It is a flexible and minimal Node.js web application framework. It provides a robust set of features. Express is a fast web framework.

Prerequisite-

For learning Express.js, you should have the basic knowledge of the following technologies-

  • JavaScript and HTML
  • js
  • Basic knowledge of MongoDB

As we know, it is a part of JavaScript, so here we are going to use some JavaScript code, and also one should be familiar with Node.js as well as MongoDB because we use MongoDB for all the database activity.

Features of Express.js

  • Rapid programming
  • Routing
  • Templating
  • Debugging
  • Set up middleware

Rapid programming (Server side)

It is facilitated with Node.js functionality. Since it's a node.js framework, it contains many of Node.js features into functions. These features can be easily called anywhere in the program. It helps Rapid application development. Express.js is quicker than Node.js. Express.js can easily do the complex task that can take too much of time in Node.js in fewer amounts of time and fewer line of code also.

Routing-

Routing is to determine how an application responds to the client's request.

Each route has at least one handler function. They are executed when the route is matched.

Express.js provides advanced and powerful routing mechanism. It can handle highly dynamic URLs. It is efficient. It defines a routing table for each route.

Templating-

Express provides a templating engine. Templating engine allowed web pages to have dynamic content by constructing HTML templates on the server side. It takes a significant load from the client side due to enabling dynamic content. Express used Pug as its templating engine. These engines are used for removing the cluttering of server code with HTML templates. Pug has various features like filter, includes, inheritance, interpolation, etc.

Debugging-

Debugging is the most complicated task for a developer. Sometimes our code may contain too many bugs then it is important to debug all that. Express.js provides a powerful mechanism for debugging. It allows developers to quickly pinpoint the part of the code causes bugs.

Middleware-

Express.js uses middleware for arranging systematically different function calls. It is a cluster of code that has access to user's request, the applications response, and the next middleware to be used. An express app. is a series of middleware function calls. These functions are the functions that have access to the request object, the response object. These functions can execute any code, make changes to the request and the response objects, end the request-respond cycle and call the next middleware function in the stack.

Middleware function can be following type-

  • Application-level
  • Error-handler
  • Router-level
  • Built-in
  • Third-party

Getting started with Express.js

Step1- install node.js and npm( node package manager)

It can be installed from its official website nodejs.org. Execute the downloaded file. Set up installing location and go through the installation process.

Now Node.js and npm have installed on your pc. So here we go for Express installation wizard.

Step2- install express module with npm command.

  • Go to command prompt and change drive for your desired location using command cd.
  • Use command npm install express --save

Now you are ready to use npm command Express.

Node pack manager-

It is a package manager for Node.js. its library is a public collection of packages of open-source code for node.js, mobile apps, web apps, routers, robots and many other needs of JavaScript community. Npm contains all the list of packages in npmJS.

npm is installed by following two ways-

1-globally- this method is for installing development tools and CLI based packages. To install the package globally use the following command-

npm install –g<package-name>

2-locally- this method is used for installing frameworks and libraries. These installation packages used within the directory it is installed. To install a package locally, use the command-

npm install < package-name>

When we create a new project by npm, we need a pakage.json file. This file has all the details about our project. npm, make it easy for set up this file.

Requests by the client-

When a basic program is written in Express.js then it creates a request by the client. These requests are different HTTP verbs.

  • GET ( it is accessing for a new web page)
  • POST ( it is for submitting the form data)
  • PUT ( for making the updation)
  • DELETE ( it is for deleting the particular record)

“Hello” world program-

var expression= require(‘express’);


var app= express();


app.get(‘/’,function(req,res)


{


Res.send(“Hello world”);


}};


App.listen(2000,function()


{


Console.log(“server started”);


}};

Output:

Hello world

Execution-

  • Open command prompt
  • go to path where npm is saved
  • type node app.js

Now the server is started. For checking the execution go to browser and in the address field type localhost:2000/ 2000 is port number so you have to type your given port number. Now enter the address you can see message by server Hello world on your web browser.

Advantages of Express.js-

  • Ultra fast input and output
  • It is simple, minimal and flexible.
  • Robust API that makes routing easy
  • MVC like structure
  • It inherits NodeJS performance.
  • Easy to configure and customize.
  • Allows to create REST API server
  • Easy database connectivity

URLRouting-

Var expression= require(‘express’);


Var app= express();


app.get(‘/’,function(req,res)


{


Console.log(“request for the homepage”);


Res.send(“Hello Home”);


}};


App.get(‘/users’,function(req,res)


{


Console.log(“ request for users page”);


Res.send(‘user page’);


}};


App.get(‘/*list’,function(req,res){


Console.log(“get request for list”);


Res.send(‘page listing’);


}};


Var server=app.listen(5000,function() { console.log(“server started”);


}};

Execution- node app.js

Server started

Browser request- localhost.5000/Home

for home page

Hello Home

How it works?

Following are some important functions and their working.

app.get(route,callback)-

This function is responsible for what to do when a get request at the given route is called. The callback has two parameters, req, and res.

The req represents the HTTP request. It has properties for the request query string, parameters, body, HTTP headers, etc. the response represents the HTTP response sent by the express app.

res.send()

This function takes the object as an input and forward it to the client.

app.method(path, handler)

Express.js Request object-

Request object in Express.js represents the HTTP request. In express.js objects of the parameter of the callback function are called Request and Response. The express.js request object has the properties for the request query string, parameter, body, HTTP headers, and so on.

Syntax-

App.get(‘/’,function(req,res)


{


- - -
----
}
}

Express.js Request object properties-

  • app it holds a reference to the instance of the express application that is using the middleware.
  • baseurl it specifies the URL path.
  • body it contains the key and value of data submitted in the request body. It is undefined by default. It is populated when body parser is used.
  • cookies this property acts as an object. It contains cookies sent by the request.
  • fresh it checks for the fresh request. It is just the opposite of req.stale.
  • hostname it contains the hostname from the server.
  • ip it contains the remote IP address of the request.
  • originalurl this property is similar to req.url. It retains original request URL. It allows you to rewrite req.url for internal writing purpose.
  • params it is an object containing properties mapped to the named route.
  • path it contains the path of the request URL.

Express.js Index

  • Express.js Tutorial
  • Express.js Installation
  • Express.js Routing
  • Express.js Middleware
  • Express.js Templates
  • Express.js Form Data
  • Express.js Sessions and Cookies
  • Express.js Authentication
  • Express.js Database
  • Express.js RESTful API’s
  • Express.js Scaffolding
  • Express.js Error Handling