Home >> Interviews Q & A >> Top 10 Express Js Interview Questions and Answers

Top 10 Express Js Interview Questions and Answers

Top 10 Express Js Interview Questions and Answers, 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 can we allow CORS in Express JS? Explain with an Example?
In order to allow CORS in Express.js, add the following code in app.js:
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();
});
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?
"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.

An Express application can use the following types 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
1. Application-level middleware:

This kind of middleware method is bind to the app Object using app.use() method.

//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 works in the same way as application-level middleware, except it is bound to an 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 number of third party middleware, such as body-parser cookie-parser, mongoose and so on.

To handle HTTP POST request in Express.js version 4 and above, you need to install 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 }))
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
Full Stack Tutorials

Author @FullStackTutorials | View all Articles