Q:- What is Express JS?
- Express.js is a free open-source, flexible node.js web application framework.
- It is designed for building backend web applications and APIs, etc.
- It has been developed by TJ Holowaychuk in 2010 and written in JavaScript.
Express.js key features:
Following are the key features of express framework:
- Middlewares: Express middleare are functions that access of - request (req), response (res) and next().
- Routing: It is used to define routes in order to perform and handle HTTP requests/operations.
- Templates Engine: It has SSR renders html template used to render the HTML on the browser.
- High Performance: Express prepare a thin layer, therefore, the performance is adequate.
- Database Support: Express supports RDBMS as well as NoSQL databases - MySQL, MongoDB, etc.
- MVC Support: It is a web application which supports MVC architecture.
- ORM Support: It support various ORM/ODM - Mongoose, Sequelize, etc.
Q:- What is Scaffolding in Express.js?
Scaffolding is creating the skeleton structure of application
There are 2 way to do this, by using:
- Express Application Generator
- Yeoman
1. Express Application Generator:
Use express-generator tool to quickly create an skeleton of your application.
npm install -g express-generator
express myTestExpressApp
Th above command will create your project named - myTestExpressApp with followings.
- bin:It is also called www is the main configuration file of the app.
- public:It contains static assets - javascript, css, images, etc.
- routes: It contains route files of the app.
- views: It contains the view files (HTML) of the application.
- app.js: It is the main file of the application which execute first.
- package.json: It is the manifest file. It contains all metadata info of the project.
Install all the dependencies mentioned in the package.json file:
cd myTestExpressApp
npm install
Q:- 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:- Serving static files in Express.js?
app.use(express.static('public'))
app.use('/static', express.static(path.join(__dirname, 'public')));
Q:- What is routing and how routing works in Express.js?
Routing refers to determining how an application responds to a request.
Route Syntax:
app.METHOD(PATH, HANDLER);
Where:
- app is an instance of express.
- METHOD is an HTTP request method (get, post, put, etc.).
- PATH is a path/endpoint on the server.
- HANDLER is a function executed when the route is matched.
#Example: A route with path / and get method.
app.get('/', function (req, res) {
res.send('Express.js Interview Questions')
})
Q:- How dynamic routing 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 request.
Q:- What is Middleware in express.js?
Middleware is a function that is invoked by the express routing layer before the final request processed.
Middleware functions can perform the following tasks:
- Execute any code - validation, setting headers, etc.
- You can make changes to the request (req) and response (res) objects.
- You can also end the request-response cycle, if rquired.
- You can call the next middleware function in the stack to proceed and process the final request.
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.
Types of Middleware:
- Application-level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- 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:
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.
- express.urlencoded parses incoming requests with URL-encoded payloads.
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, this 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:- Database integration in express.js?
Express.js supports of many RDBMS & NoSQL databases 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:- Error handling in Express.js?
var express = require('express'),
app = express();
app.use(function (err, req, res, next) {
console.error(err.stack) // error first callback
res.status(500).send('Something went wrong!')
})
var express = require('express'),
app = express();
app.use(function(req, res, next) {
res.status(404).json({
errorCode: 404,
errorMsg: "Not found!"
});
});
Q:- 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
- res.setHeader() - It allow to set only single header
- res.header() OR res.set() - It allow to set multiple headers.
- 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:- 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
Was this interview questions answers helpful?
Share now with your friends!