Google News
logo
Express.js Interview Questions
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.
 
It is developed by TJ Holowaychuk on 16th November 2010. This is where Express.js shines and does the one job perfectly for which it was created, which is, creating API endpoints. It adds the functionality of middleware and routing with ease in a Node.js application.
Node.js is a platform for building the i/o applications which are server-side event-driven and made using JavaScript.

Express.js is a framework based on Node.js for which is used for building web-application using approaches and principles of Node.js.event-driven.

Feature Express.js Node.js
Usage It is used to build web-apps using approaches and principles of Node.js.  It is used to build server-side, input-output, event-driven apps.
Level of features More features than Node.js. Fewer features.
Building Block It is built on Node.js. It is built on Google’s V8 engine.
Written in JavaScript C, C++, JavaScript
Framework/Platform Framework based on Node.js. Run-time platform or environment designed for server-side execution of JavaScript.
Controllers Controllers are provided. Controllers are not provided.
Routing Routing is provided. Routing is not provided.
Middleware Uses middleware for the arrangement of functions systematically server-side. Doesn’t use such a provision.
Coding time It requires less coding time. It requires more coding time.
Installing 

Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory.
$ mkdir myapp
$ cd myapp
Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.
$ npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception :
entry point: (index.js)
Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.
 
Now install Express in the myapp directory and save it in the dependencies list. For example :
$ npm install express
To install Express temporarily and not add it to the dependencies list :
$ npm install express --no-save
Express.js is a JavaScript backend framework. It is mainly designed to develop complete web applications (single-page, multi-page, and hybrid web applications) and APIs. Express is the backend component of the MEAN stack where M stands for MongoDB, which handles database; E stands for Express, which handles backend; A stands for AngularJS, which is for the front-end, and N stands for Node.
Express.js is an automatically prebuilt Node.js framework that facilitates us to create server-side web applications faster and smarter. The main reason for choosing Express is its simplicity, minimalism, flexibility, and scalability characteristics.
Generators are used by yeoman for scaffolding the applications. And we can use the following command to install yeoman.
npm install –g yeoman
The arguments which are available to an Express JS route handler-function are :
 
Req : the request object
Res : the response object
Next (optional) : a function that is employed to pass management to 1 of the following route handlers.

The third argument is optional and should be omitted, however, in some cases, it’s helpful wherever there’s a series of handlers and management will be passed to 1 of the following route handlers skipping this one.
In Express JS, there are 2 ways that for configuring the properties:
 
With process.ENV :
 
* A file with the name “.env” is to be created within the project folder.
* All the properties are to be other within the “.env” file.
* Any of the properties will be employed in server.js.

With require.JS :
 
* A file with the name “config.json” is to be created within the config folder within the project folder.
* The config properties are to be present within the config.json file.
* Now, ought to be accustomed access the config.json file.
There is no definitive answer to the current question. The solution depends on the dimensions of your application and therefore the team that’s concerned.

Routes and alternative application-Express logic will board as several files as you would like, in any directory structure you favor. Read the subsequent examples for inspiration :
 
* Route listings
* Route map
* MVC vogue controllers

Also, there are third-party extensions for Express JS applications that modify a number of these patterns:
Resourceful routing
As Express is a lightweight, minimal and flexible Node.js web application framework, it provides a robust set of features for web and mobile applications. Following is the list of some distinctive features of this framework :
 
* js can be used to design single-page, multi-page, and hybrid web applications and APIs.
* It allows to set up middleware to respond to HTTP/RESTful Requests.
* It defines a routing table to perform different HTTP operations (method and URL).
* It allows to dynamically rendering HTML Pages based on passing arguments to templates.
* It provides high performance because of its ultra-fast I/O. It prepares a thin layer; therefore, the performance is adequate.
* Its MVC-like structure makes it organize the web application into MVC architecture.
* It provides good database support. It supports RDBMS as well as NoSQL databases.
* It is asynchronous and single-threaded.
* Its robust API makes routing easy.
The express.js program is saved with ".js" extension.
 
Example :
var express = require('express');    
var app = express();    
app.get('/', function (req, res) {    
  res.send('Welcome to Free Time Learning!');    
});    
var server = app.listen(8000, function () {    
  var host = server.address().address;    
  var port = server.address().port;    
  console.log('Example app listening at http://%s:%s', host, port);    
});  ​
 
When you run the Node.js command prompt, the app will listen at the specified server address and give the following output.
 
Output :
Welcome to Free Time Learning!
var bodyParser = require('body-parser')  
app.use( bodyParser.json() );       // to support JSON-encoded   
app.use(bodyParser.urlencoded({     // to support URL-encoded   
  extended: true  
}));  
In order to permit CORS in Express.js, add the subsequent code in server.js :
 
Example :
app.all('*', function(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
if ('OPTIONS' == req.method) return res.send(200);
next();
});
In different operative Systems, we’ve got following commands :
 
On Linux (or) UNIX operating system the command would be as follows :
$ DEBUG=express:* node index.js
On Windows the command would be :
set DEBUG=express:* & node index.js
From Webstrome IDE
C:\Program Files (x86)\JetBrains\WebStorm 2016.2.4\bin\runnerw.exe"
"C:\Program Files\nodejs\node.exe" --debug-brk=61081 --expose_debug_as=v8debug
E:\Development\nodejd\librarey\bin\www
Express.js provides the following built-in middleware functions :
 
Static : We use it for serving static assets like images, HTML files, etc.

JSON : This is available in Express 4.16.0+. And we use it for passing the incoming requests with JSON payloads.

URL encoded : This is also available in Express 4.16.0+. And we use it for passing the incoming requests with URL-encoded payloads.
Third-party Middleware: There are many third-party middleware available such as :
 
* Body-parser
* Cookie-parser
* Mongoose
* Sequelize
* Cors
* Express-validator
 
To handle HTTP POST requests in Express.js version 4 and above, we have to install a middleware module called body-parser. Body-parser extracts the entire body portion of an incoming request stream and exposes it on req. body, The Middleware was a part of Express.js earlier, but now you have to install it separately. You can install it by using the following command :
npm install MODULE_NAME  
You can load it by using requires and used later:
 
See the Example :
var bodyParser = require('body-parser');  
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: false }))  
Note: You can use multiple middleware as an array on a single route.
See the Example :
var middlewareArray = [middleware1, middleware2]  
app.get('/home', middlewareArray, function (req, res, next) {  
  //Code snippets  
})  
Scaffolding is a technique used for creating the skeleton structure of an application. It facilitates users to easily create their public directories, routes, views, etc., or a web application skeleton. Generally, users manually create their public directory, add middleware, create separate route files, etc. Using a scaffolding tool, they can set up all these things to directly get started with building their application.
 
There are two ways to install Scaffolding and use it in your application.
 
* Express application generator
* Yeoman

Express application generator : This is used to create an application skeleton quickly. Use the following command to install the Express application generator.
npm install express-generator -g  
express myApp  
By using the above command, a project named "myApp" will be created along with following the files/folders in the project.
 
Bin : The bin folder contains one file called www is the main configuration file of the app.
Public : The public folder contains JavaScript, CSS, and images, etc.
Routes : This folder contains the routing files.
Views : The view folder contains the view files of the application.
js : The app.js file is the main file of the application.
json : The package.json file is the manifest file. It contains all metadata of the project, such as the packages used in the app (called dependencies) etc.
 
Now, we have to install all the dependencies mentioned in the package.json file by using the following command :
cd myApp  
npm install
Yeoman : Use the following command in your terminal to install Yeoman :
npm install -g yeoman  
Yeoman uses generators to scaffold out applications.
The Scaffolding technique is also supported by other MVC frameworks other than Express. The following frameworks mainly support it: Ruby on Rails, OutSystems Platform, Play framework, Django, MonoRail, Brail, Symfony, Laravel, CodeIgniter, YII, CakePHP, Phalcon PHP, Model-Glue, PRADO, Grails, Catalyst, Seam Framework, Spring Roo, ASP.NET, etc.
Django is a standalone and lightweight web server for testing and development. On the other hand, Express.js is a Node.js framework that can set the middleware to reply to any HTTP request.

Aspects Express.js Django
Architecture Express follows the MVC architecture. Django supports the MTV (Model Template View) design. It uses managing data for interacting and validating.
Framework Express is a free, open-source, lightweight, and fast backend web application framework for Node.js to build single-page, multi-page, and hybrid web applications and APIs. This is a Python-based framework used to develop computer apps in a specified time frame.
Efficiency It is best for developing web applications rapidly on Node.js. It is more efficient and delivers at a fast speed so, it is cost-effective.
Programming language The Express framework is programmed in Node.js. Django is programmed in Python programming language.
Complexity Express.js is less complex than Django. Django is more complex than Express.js
Scalability It provides better scalability. It is less scalable.
Flexibility Express is a flexible, minimal API-developing Node.js tool. It provides limited flexibility.
Full-stack development It provides a full-stack development that reduces the cost as you don't need to hire several developers to administer a web application's backend and frontend. It does not deliver full-stack development.
Companies using this technology Companies such as PayPal, IBM, Fox Sports, etc., are using this technology. Companies such as Instagram, Mozilla, Bitbucket, etc., are using this technology.
Error handling is much easier in the Express versions over Express 4.0. Use the following steps to do the error handling:
 
Create an Express.js application. There is no built-in middleware like error handler in express 4.0, so you have to either install a middleware or create a custom one.
 
Create a Middleware :
 
Create a middleware as following:
// error handler  
app.use(function(err, req, res, next) {  
// set locals, only providing error in development  
res.locals.message = err.message;  
res.locals.error = req.app.get('env') === 'development' ? err : {};  
// render the error page  
res.status(err.status || 500);  
res.render('error');  
}); ​
 
Install Error Handler Middleware :
 
Install the errorhandler as following :
npm install errorhandler --save  
Create a variable :
var errorhandler = require('errorhandler')  
Use the middleware as following :
if (process.env.NODE_ENV === 'development') {  
 // only use in development  
  app.use(errorhandler({log: errorNotification}))  
}  
function errorNotification(err, str, req) {  
 var title = 'Error in ' + req.method + ' ' + req.url  
 notifier.notify({  
   title: title,  
   message: str  
 })  
}  
See the Example :
app.use(express.static('public'))  
app.use('/static', express.static(path.join(__dirname, 'public')))  
The following HTTP methods are the most used ones :
 
GET : A specified resource's representation is requested by the GET method. These requests can only retrieve data.

POST : Posting of the data enclosed in the request as a new entity is done using the POST method. The entity is identified by the URI.

PUT : Modification in the existing entity is done with the data enclosed in the request identified by the URI.

DELETE : The request for deleting the specified source is made by the DELETE method.
A cross-Origin can fail in the following scenarios-
 
* If it's to a different domain
* If it's to a different port
* If it's to a different subdomain
* If it's to a different protocol.
We will first install it using the given command:
npm install pug
Then we will set it as following when initializing the Express app :
const express = require ('express')
const app = express()
app.set ('view engine', 'pug')
Next -It passes management to a consecutive matching route. OR a operate to pass management to 1 of the following route handlers.

The argument could also be omitted, however, is beneficial in cases wherever you have got a series of handlers and you’d wish to pass management to 1 of the following route handlers, and skip this one.
app.get('/user details/:id?', function(req, res, next));
* Req and Res : It represents the request and response objects

* Next :
It passes management to a consecutive matching route.
In server.js add the subsequent code to send 404 errors back to a page in our ExpressJS App :
/* Define fallback route */
app.use(function(req, res, next) {
res.status(404).json({errorCode: 404, errorMsg: "route not found"});
});
The application-level middleware method is used to bind to the app object using app.use() method. It applies on all routes.
//This middleware will execute for each route.  
app.use(function (req, res, next) {  
  console.log('Current Time:', Date.now())  
  next()  
})  
The router-level Middleware is used to bind to a specific instance of express.Router().Built-in Middleware : The built-in Middleware was introduced with version 4.x. It ends the dependency on Connect.
 
There are the following built-in middleware functions in Express.js :
 
* static : It is used to serve static assets such as HTML files, images, etc.

* json : It is used to parse the incoming requests with JSON payloads. It is available with Express 4.16.0+

* urlencoded : It is used to parse the incoming requests with URL-encoded payloads. It is available with Express 4.16.0+
We can call the following methods in such cases -
 
File.name : the name of the file

File.path : the path to which the file is written

File.size : the size of the file in bytes

File.type : the file's MIME-type.
Cluster :
 
* Each CPU has one process with an IPC to communicate.
* Clusters help when multiple servers are required to accept HTTP requests through a single port.
* The processes have separate memory because of being spanned in different CPUs leading to memory issues.

Worker Threads :
 
* Only a single process is there with multiple threads.
* Each Node contains one Node having most APIs accessible.
* The memory is shared with other threads.
* We can use this for CPU-intensive tasks.
It's a class of Node JS capable of emitting events. We do this by attaching the named events emitted by the object by using the function- eventEmitter.on().
The server initializes the Middleware, routes, and other application logic. On the other hand, the app contains all the business logic that the server-initiated routes will serve. This enables the encapsulation of the business logic from the application logic for smooth functioning.
The options available are given below :
 
* --sessions or –s for adding session report

* --hogan or –H for adding Hogan.js engine support

* --ejs or –e for adding EJS engine support

* --css <engine> or –c <engine> for adding style sheet support

* -jshtml or –J for adding JSHTML engine support

* --force or –f for forcing app generation on the directory which is non-empty.
We will follow the given steps to set up HTTP :
 
* Installing certbot
* Generating the SSL certificate by Certbot
* Allowing Express to serve the static files
* Confirming the domain
* Obtaining the certificate
* Setting up the renewal.
When running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the trust proxy application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client’s IP address may instead show an internal IP address of the reverse proxy.
 
The application setting trust proxy may be set to one of the values listed in the following table.

Type Value
Boolean

If true, the client’s IP address is understood as the left-most entry in the X-Forwarded-For header.

If false, the app is understood as directly facing the client and the client’s IP address is derived from req.socket.remoteAddress. This is the default setting.

IP addresses

An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names:

  • loopback - 127.0.0.1/8, ::1/128
  • linklocal - 169.254.0.0/16, fe80::/10
  • uniquelocal - 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7

You can set IP addresses in any of the following ways:

app.set('trust proxy', 'loopback') // specify a single subnet
app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address
app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array

When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address. This works by checking if req.socket.remoteAddress is trusted. If so, then each address in X-Forwarded-For is checked from right to left until the first non-trusted address.

Number

Use the address that is at most n number of hops away from the Express application. req.socket.remoteAddress is the first hop, and the rest are looked for in the X-Forwarded-For header from right to left. A value of 0 means that the first untrusted address would be req.socket.remoteAddress, i.e. there is no reverse proxy.

Function

Custom trust implementation.

app.set('trust proxy', (ip) => {
  if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs
  else return false
})

Enabling trust proxy will have the following impact :

* The value of req.hostname is derived from the value set in the X-Forwarded-Host header, which can be set by the client or by the proxy.  
* X-Forwarded-Proto can be set by the reverse proxy to tell the app whether it is https or http or even an invalid name. This value is reflected by req.protocol.
* The req.ip and req.ips values are populated based on the socket address and X-Forwarded-For header, starting at the first untrusted address.
Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app :
 
* Cassandra
* Couchbase
* CouchDB
* LevelDB
* MySQL
* MongoDB
* Neo4j
* Oracle
* PostgreSQL
* Redis
* SQL Server
* SQLite
* Elasticsearch
Express 5.0 is still in the beta release stage, but here is a preview of the changes that will be in the release and how to migrate your Express 4 app to Express 5.
 
To install the latest beta and to preview Express 5, enter the following command in your application root directory :
$ npm install "express@>=5.0.0-beta.1" --save