Top 10 Express.js Interview Questions and Answers, Express Js Interview Questions, Express.js Interview Questions
Express.js Interview Questions
Q.1) What is Express.js?
  1. Express.js is a free open-source, light-weight node js based web application framework.
  2. It is designed for building (single-page, multi-page, and hybrid) web applications and APIs.
  3. It has been developed by TJ Holowaychuk in 2010 and written in JavaScript.
Express.js Features:

Following are some of the core features of Express framework:

  1. Middlewares: Set up middlewares in order to respond to HTTP/RESTful Requests.
  2. Routing: It is possible to defines a routing table in order to perform different HTTP operations.
  3. Templates: Dynamically renders HTML Pages based on passing arguments to templates.
  4. High Performance: Express prepare a thin layer, therefore, the performance is adequate.
  5. Database Support: Express supports RDBMS as well as NoSQL databases.
  6. MVC Support: Organize the web application into an MVC architecture.
  7. Manages everything from routes to rendering view and preforming HTTP request.
Q.2) How to allow CORS in Express.js (Node.js)? Explain with an Example?

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources to be requested from another domain/server.

There are mainly three ways you can do this using
  1. res.setHeader() - It allow to set only single header
  2. res.header() OR res.set() - It allow to set multiple headers.
  3. express cors module
1. Enable CORS for all resources using res.setHeader().
app.use(function(req, res, next) { // Website you wish to allow to connect res.setHeader("Access-Control-Allow-Origin", "*"); // Request methods you wish to allow res.setHeader( "Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE" ); // Request headers you wish to allow res.setHeader( "Access-Control-Allow-Headers", "X-Requested-With,content-type" ); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader("Access-Control-Allow-Credentials", true); // Pass to next layer of middleware next(); });
2. Enable CORS for all resources using res.header()
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept" ); next(); });
3. Enable CORS for all resources using express CORS module.

If you are using express.js you can use cors module

3.1) Enable CORS Requests for All Servers.
var express = require("express"); var cors = require("cors"); var app = express(); app.use(cors()); app.get("/", function(req, res, next) { res.json({ msg: "This is CORS-enabled for all origins!" }); }); app.listen(80, function() { console.log("CORS-enabled web server listening on port 80"); });
3.2) Enable CORS Requests for Some Specific Servers
var express = require("express"); var cors = require("cors"); var app = express(); var whitelist = ["http://server1.com", "http://server2.com"]; var corsOptions = { origin: function(origin, callback) { if (whitelist.indexOf(origin) !== -1) { callback(null, true); } else { callback(new Error("Not allowed by CORS")); } } }; app.get("/", cors(corsOptions), function(req, res, next) { res.json({ msg: "This is CORS-enabled for a whitelisted domain." }); }); app.listen(80, function() { console.log("CORS-enabled web server listening on port 80"); });
You may also like - Node.js Interview Questions Answers
Q.3) What is Scaffolding in Express.js?

Scaffolding is creating the skeleton structure of application

There are 2 way to do this:

  1. Express application generator
  2. Yeoman
1. Express application generator:

Use express-generator to quickly create an application skeleton.

npm install express-generator -g express myTestExpressApp

Th above command will create your project named - myTestExpressApp with following the files/folders in project.

  1. bin:The bin folder have one file called www is the main configuration file of our app.
  2. public:Public folder contains JavaScript, CSS, images etc.
  3. routes: Routes folder contains routing files.
  4. views: View folder contains the view files of the application.
  5. app.js: The app.js file is the main file of the application.
  6. package.json: 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.

Install all the dependencies mentioned in the package.json file:

cd myTestExpressApp npm install
Q.4) How to enable debugging in express app?

In different Operating Systems, we have following commands:

On Linux:

DEBUG=express:* node app.js

On Windows:

set DEBUG=express:* node app.js
Q.5) Serving static files in Express?
#Example: app.use(express.static('public')) app.use('/static', express.static(path.join(__dirname, 'public')))
Q.6) What is routing and how routing works in Express.js?
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 (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route Syntax:
app.METHOD(PATH, HANDLER)

Where:

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.

#Example:

app.get('/', function (req, res) { res.send('Express.js Interview Questions') })
Dynamic routing and how it works in Express.js?

When someone pass parameters in URL i.e. Parametrized URL, this routing phenomenon is called dynamic routing.

var express = require('express'), app = express(); app.get('/article/:id', function(req , res){ res.render('article' + req.params.id); })

In above example: id is a parameters, which can be different for different calls.

Q.7) What is Middleware in Express.js?
Middleware is a function that is invoked by the Express routing layer before the final request handler.
Middleware functions can perform the following tasks:
  1. Execute any code.
  2. Make changes to the request and the response objects.
  3. End the request-response cycle.
  4. Call the next middleware function in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Type of Middleware:
  1. Application-level middleware
  2. Router-level middleware
  3. Error-handling middleware
  4. Built-in middleware
  5. Third-party middleware
You may also like - React.js Interview Questions Answers
1. Application-level middleware:

This kind of middleware method is 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() })
2. Router-level middleware:

Router-level middleware binds to an specific instance of express.Router()

3. Built-in middleware:

Starting with version 4.x, Express no longer depends on Connect.

Express has the following built-in middleware functions:

  • express.static serves static assets such as HTML files, images, and so on.
  • express.json parses incoming requests with JSON payloads.
    NOTE: Available with Express 4.16.0+
  • express.urlencoded parses incoming requests with URL-encoded payloads.
    NOTE: Available with Express 4.16.0+
4. Third-party middleware:

There are a lots of third party middleware, such as

  • Body-parser
  • Cookie-parser
  • Mongoose
  • Sequelize
  • Cors
  • Express-validator

To handle HTTP POST request in Express.js version 4 and above, you need to install a middleware module called body-parser, body-parser extract 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.

These can be installed by using command:

>> npm install MODULE_NAME

And they can be loaded using requires and used later.

#Example:
var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }))

Note: Multiple Middleware can be used as an array on a single route.

var middlewareArray = [middleware1, middleware2] app.get('/home', middlewareArray, function (req, res, next) { //Code snippets })
Q.8) Database integration in Express.js?

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

Express.js supports many RDBMS & NoSQL Ddatabase like
  • MongoDB
  • MySQL
  • Oracle
  • PostgreSQL
  • SQL Server
  • SQLite
#Example: Install MongoDB
>>npm install mongodb var MongoClient = require('mongodb').MongoClient MongoClient.connect('mongodb://localhost:27017/test_db', function (err, db) { if (err) throw err db.collection('mammals').find().toArray(function (err, result) { if (err) throw err console.log(result) }) })
Q.9) Error handling in Express.js and How to redirect 404 errors to a page in Express.js?
var express = require('express'), app = express(); app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something went wrong, Express.js Interview Questions') })
//To redirect 404 errors var express = require('express'), app = express(); app.use(function(req, res, next) { res.status(404).json({ errorCode: 404, errorMsg: "route not found" }); });
Q.10) How to implement JWT authentication in Express app ? Explain with an Example?
  • Create a folder called 'keys' inside project folder.
  • Install some dependencies as following: npm install jsonwebtoken –-save
  • Add the login router routes/index.js
  • router.post('/login, function(req, res) { // find the user User.findOne({ name: req.body.username }, function(err, res) { if (err) throw err; if (!res) { res.json({ success: false, message: Login failed.' }); } else if (res) { // check if password matches if (res.password != req.body.password) { res.json({ success: false, message: Login failed. Wrong password.' }); } else { var token = jwt.sign(res, app.get('superSecret'), { expiresInMinutes: 1600 }); // return the information including token as JSON res.json({ success: true, message: 'Valid token!', token: token }); } } }); });
  • Use the token in application
  • jwt = require("express-jwt"); app.use(function(req, res, next) { var token = req.body.token || req.query.token || req.headers['x-access-token']; if (token) { jwt.verify(token, app.get('superSecret'), function(err, decoded) { if (err) { return res.json({ success: false, message: 'Invalid token.' }); } else { req.decoded = decoded; next(); } }); } else { return res.status(403).send({ success: false, message: 'No token given.' }); } });
You may also like - Angularjs Interview Questions