The Top 100 Interview Questions On Express - Js
The Top 100 Interview Questions On Express - Js
js
1. What is Express.js?
Answer: Express.js is a popular web application framework for Node.js that provides a simple and
flexible way to build web applications and APIs.
Answer: The key features of Express.js include routing, middleware support, template engine
integration, error handling, and support for various HTTP methods.
Answer: You can install Express.js using npm (Node Package Manager) by running the command:
`npm install express`.
Answer: To create a new Express.js application, you need to require the express module and create
an instance of the Express application using the following code:
javascript
Answer: You can start a server using Express.js by calling the `listen` method on the Express
application instance and specifying the port number, as shown below:
javascript
app.listen(3000, () => {
});
Answer: You can use middleware in Express.js by calling the `use` method on the Express application
instance and passing the middleware function as an argument. Middleware functions can be defined
inline or in separate modules.
- Application-level middleware: It is bound to the Express application and is used for tasks that are
specific to the application, such as logging and error handling.
- Router-level middleware: It is bound to a specific router and is used for tasks related to that router,
such as authentication and request preprocessing.
- Error-handling middleware: It is used to handle errors that occur during the request-response
cycle.
- Third-party middleware: These are external middleware modules that can be used to add
additional functionality to the application.
Answer: Routing in Express.js is handled using the `express.Router` class. You can create an instance
of the Router class, define routes on it, and then mount the router on the main Express application
using the `app.use` method.
Answer: You can define a route in Express.js by calling the appropriate method on the Express
application or router instance, specifying the HTTP method and the route path, and providing a
callback function to handle the request.
Example:
javascript
});
11. How do you handle HTTP GET requests in Express.js?
Answer: You can handle HTTP GET requests in Express.js by using the `get` method on the Express
application or router instance, specifying the route path and providing a callback function to handle
the request.
Answer: You can handle HTTP POST requests in Express.js by using the `post` method on the Express
application or router instance, specifying the route path and providing a callback function to handle
the request.
Express.js by using the `put` method on the Express application or router instance, specifying the
route path and providing a callback function to handle the request.
Answer: You can handle HTTP DELETE requests in Express.js by using the `delete` method on the
Express application or router instance, specifying the route path and providing a callback function to
handle the request.
Answer: The `next` function is used in Express.js middleware to pass control to the next middleware
function in the chain. It is typically called inside a middleware function to allow the application to
continue processing subsequent middleware or routes.
Answer: You can handle errors in Express.js by defining an error-handling middleware function with
four parameters: `(err, req, res, next)`. This function is called whenever an error occurs in the
request-response cycle. You can handle the error and send an appropriate response to the client.
Example:
javascript
app.use((err, req, res, next) => {
console.error(err);
});
Answer: The `app.use()` method is used to mount middleware functions on the Express application.
It can be used to define application-level middleware or to mount routers or other middleware at a
specified route.
Answer: You can serve static files in Express.js by using the `express.static` middleware function and
specifying the directory from which to serve the files.
Example:
javascript
app.use(express.static('public'));
Answer: The `req` object in Express.js represents the request made by the client to the server. It
contains information about the request, such as the URL, HTTP headers, query parameters, request
body, and more.
Answer: The `res` object in Express.js represents the response that will be sent back to the client. It
is used to send the response data, set response headers, and perform other operations related to
the response.
Answer: The `app.locals` object in Express.js provides a way to pass data from the server to views or
templates. It is an object that is available in all views rendered by the application.
Example:
javascript
Answer: You can access query parameters in Express.js through the `req.query` object. It contains
key-value pairs of the query parameters sent with the request.
Example:
javascript
// GET /users?name=John&age=25
console.log(req.query.age); // Output: 25
Answer: You can access request headers in Express.js through the `req.headers` object. It contains
key-value pairs of the headers sent with the request.
Example:
javascript
console.log(req.headers['content-type']);
Answer: To access request body data in Express.js, you need to use middleware such as `body-
parser` or the built-in `express.json` middleware. Once the middleware is set up, you can access the
parsed request body through the `
req.body` object.
Example with `body-parser` middleware:
javascript
app.use(bodyParser.json());
console.log(req.body);
});
Answer: You can set response headers in Express.js by using the `res.set()` method or by directly
assigning values to the `res.headers` object. The headers must be set before sending the response.
Example:
javascript
res.set('Content-Type', 'application/json');
Answer: You can redirect a request in Express.js by using the `res.redirect()` method and specifying
the URL to redirect to. The status code for the redirect is set to 302 by default.
Example:
javascript
res.redirect('/new-page');
Example:
javascript
});
app.use('/api', router);
Answer: You can implement sessions in Express.js by using middleware such as `express-session`.
This middleware creates and manages a session object for each client and allows you to store
session data and access it across requests.
javascript
app.use(session({
secret: 'my-secret-key',
resave: false,
saveUninitialized: true
}));
app.get('/counter', (req, res) => {
if (req.session.views) {
req.session.views++;
} else {
req.session.views = 1;
res.send(`Views: ${req.session.views}`);
});
javascript
app.use(passport.initialize());
res.send('Logged in successfully');
});
Example:
javascript
next();
} else {
res.status(403).send('Forbidden');
};
res.send('Welcome, admin');
});
Answer: You can handle file uploads in Express.js by using middleware such as `multer`. Multer is a
popular middleware that provides support
javascript
console.log(req.file);
});
Answer: Express generator is a command-line tool that helps in generating the basic structure and
files for an Express.js application. It sets up the application with default configurations, including the
file structure, routing, middleware, and package.json.
To use Express generator, you need to install it globally using npm: `npm install -g express-
generator`. Then, you can create a new Express application using the `express` command followed
by the application name.
Example:
bash
express myapp
cd myapp
npm install
Answer: Route handlers in Express.js are callback functions that are executed when a specific route
is matched. They handle the logic for processing the request and sending the response.
Example:
javascript
});
Answer: You can pass data to route handlers in Express.js by using route parameters or query
parameters.
javascript
});
javascript
});
Answer: Pagination in Express.js can be implemented by using query parameters to control the
number of items per page and the page number. In the route handler, you can use these parameters
to retrieve the appropriate subset of data to send back as the response.
Example:
javascript
res.send(users);
});
Answer: Caching in Express.js can be implemented by using middleware functions such as `response-
time` and `express-cache-headers`. These middleware functions add caching headers to the
response, allowing the client or intermediate caches to cache the response and serve it for
subsequent requests.
javascript
app.use(cacheHeaders());
res.setCacheHeaders({
maxAge: 60,
private: true
});
res.send(users);
});
Answer: You can handle CORS (Cross-Origin Resource Sharing) in Express.js by using middleware
such as `cors`. CORS middleware adds the necessary headers to allow cross-origin requests from
specified domains.
javascript
const express
= require('express');
app.use(cors());
});
Answer: Express.js does not provide built-in support for WebSocket connections. However, you can
use external libraries such as `socket.io` to handle WebSocket connections alongside your Express.js
application.
const io = require('socket.io')(server);
});
socket.on('disconnect', () => {
});
});
server.listen(3000, () => {
});
Answer: You can handle cookies in Express.js by using the `cookie-parser` middleware. This
middleware parses the cookies sent by the client and makes them available in the `req.cookies`
object.
javascript
app.use(cookieParser());
});
Answer: You can define route-specific middleware in Express.js by adding the middleware functions
as additional arguments before the route handler function in the route definition.
Example:
javascript
console.log('Log middleware');
next();
};
console.log('Route middleware');
next();
};
app.get('/users', logMiddleware, routeMiddleware, (req, res) => {
res.send('Users');
});
Answer: You can set response headers in Express.js using the `res.set()` or `res.header()` methods.
These methods allow you to specify the headers and their values to be included in the response.
Example:
javascript
res.set('Content-Type', 'application/json');
res.set({
'Cache-Control': 'no-cache',
});
});
52. How do you handle JSON data in the request body in Express.js?
Answer: You can handle JSON data in the request body in Express.js by using the `express.json()`
middleware. This middleware automatically parses JSON data sent in the request body and makes it
available in `req.body`.
Example:
javascript
app.use(express.json());
});
53. How do you handle URL-encoded form data in the request body in Express.js?
Answer: You can handle URL-encoded form data in the request body in Express.js by using the
`express.urlencoded()` middleware. This middleware parses the URL-encoded data sent in the
request body and makes it available in `req.body`.
Example:
javascript
});
Answer: You can handle request validation in Express.js by using validation middleware such as
`express-validator`. This middleware allows you to define validation rules for the request body,
query parameters, route parameters, and headers.
javascript
app.post('/users', [
body('name').notEmpty().withMessage('Name is required'),
body('email').isEmail().withMessage('Invalid email'),
if (!errors.isEmpty()) {
});
Example:
javascript
next();
};
if (req.user.isAdmin) {
next();
} else {
res.status(403).send('Forbidden');
};
});
Answer: You can handle sessions and cookies in Express.js using middleware such as `express-
session` and `cookie-parser`. The `express-session` middleware manages session data and assigns a
unique session ID to each client. The `cookie-parser` middleware parses cookies sent by the client
and makes them available in `req.cookies`.
Example:
javascript
app.use(cookieParser());
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: true,
}));
});
javascript
cb(null, 'uploads/');
},
cb(null, file.originalname);
},
});
});
Answer: You can handle Cross-Origin Resource Sharing (CORS) in Express.js using the `cors`
middleware. This middleware adds the necessary headers to enable cross-origin requests from client
applications hosted on different domains.
javascript
});
Answer: Server-side rendering (SSR) with Express.js involves rendering the initial HTML on the server
and sending it to the client. You can use templating engines like `EJS` or `Pug` to generate dynamic
HTML on the server.
javascript
});
Answer: Pagination in Express.js involves handling requests for specific pages of data. You can use
query parameters to specify the page number and limit, and then apply appropriate logic to retrieve
and display the requested data.
Example:
javascript
// Apply pagination logic (e.g., retrieve users for the specified page and limit)
res.json({
page,
limit,
});
});
Answer: You can handle request logging in Express.js by creating a middleware function that logs
information about each incoming request. This middleware can log details such as the request
method, URL, headers, and timestamps.
Example:
javascript
next();
};
app.use(requestLogger);
});
javascript
app.use(compression());
});
Answer: You can handle rate limiting in Express.js using middleware such as `express-rate-limit`. This
middleware allows you to set limits on the number of requests a client can make within a specified
time period, preventing abuse or excessive usage.
javascript
});
app.use(limiter);
});
Answer: You can handle CSRF (Cross-Site Request Forgery) protection in Express.js by using
middleware such as `csurf`. This middleware adds a CSRF token to each form or API request, and
validates the token on subsequent requests to prevent CSRF attacks.
javascript
app.use(csurf());
});
});
Answer: Express.js does not provide built-in support for WebSocket connections. However, you can
use external libraries such as `socket.io` to handle WebSocket connections alongside your Express.js
application.
javascript
const express = require('express');
const io = require('socket.io')(server);
});
socket.on('disconnect', () => {
});
});
server.listen(3000, () => {
});
Answer: You can handle server-sent events (SSE) in Express.js by using the `res.sse()` method
provided by the `express-sse` library. This method allows you to send SSE data to
javascript
const express = require('express');
app.get('/stream', sse.init);
res.sendStatus(200);
});
Answer: You can handle route prefixing in Express.js by using the `express.Router` middleware. This
middleware allows you to create modular route handlers that can be mounted to a specific path
prefix.
Example:
javascript
});
});
app.use('/api', router);
Answer: You can handle custom 404 errors in Express.js by defining a middleware function that runs
after all other route handlers. This middleware function can be used to handle requests that don't
match any route, returning a custom 404 error message.
Example:
javascript
});
Answer: Long-polling is a technique used for real-time communication between a client and a server.
While Express.js does not provide built-in support for long-polling, you can implement it by
combining techniques such as event emitters and timeouts.
Example:
javascript
// Long-polling implementation
clearInterval(intervalId);
res.json({ newData: true });
}, 1000);
});
70. How do you handle multiple callback functions in a route handler in Express.js?
Answer: You can handle multiple callback functions in a route handler in Express.js by passing an
array of callback functions as the second argument to the route handler. Each callback function is
executed in the order they appear in the array.
Example:
javascript
next();
};
next();
};
});
Answer: Express.js does not provide built-in support for method overriding. However, you can use
middleware such as `method-override` to enable method overriding by utilizing query parameters or
headers to specify the desired HTTP method.
Example with `method-override`:
javascript
app.use(methodOverride('_method'));
});
Answer: Server-side validation in Express.js involves validating the data received from the client to
ensure it meets certain criteria or business rules. You can use validation libraries such as `express-
validator` or custom validation logic to perform server-side validation.
javascript
app.post('/users', [
body('username').notEmpty().withMessage('Username is required'),
if (!errors.isEmpty()) {
});
73. How do you handle file downloads in Express.js?
Answer: You can handle file downloads in Express.js by setting the appropriate headers and sending
the file as a response using the `res.download()` method. This method automatically sets the
headers to trigger a file download in the client's browser.
Example:
javascript
res.download(filePath);
});
Answer: You can apply middleware to specific routes in Express.js by including them as additional
arguments in the route handler function. These middleware functions will be executed only for the
specific route they are applied to.
Example:
javascript
// Authenticate user
next();
};
// Authorize user
next();
};
app.get('/users', authenticate, authorize, (req, res) => {
});
Example:
javascript
dotenv.config();
const dbConfig = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
};
Answer: Express.js helps prevent cross-site scripting (XSS) attacks by default through template
engines such as `EJS` or `Pug`, which automatically escape HTML entities by default. It is important
to properly handle user input and sanitize data when displaying it in views.
javascript
});
Answer: To handle HTTPS and SSL certificates in Express.js, you need to create an HTTPS server using
the `https` module and provide the necessary SSL certificate files. You can obtain SSL certificates
from certificate authorities like Let's Encrypt.
Example:
javascript
const fs = require('fs');
const options = {
key: fs.readFileSync('path/to/privateKey.pem'),
cert: fs.readFileSync('path/to/certificate.pem'),
};
server.listen(443, () => {
});
javascript
});
Answer: Express.js has a default request size limit of 100kb for request bodies. To handle large
request bodies, you can use middleware such as `body-parser` or `multer` to increase the size limit
or handle streaming large files.
javascript
});
javascript
});
Answer: You can handle route-specific error handling in Express.js by defining error-handling
middleware functions that are specific to certain routes. You can use the `app.use()` method to
apply these middleware functions after the route handlers for the specific routes.
Example:
javascript
});
});
92. How do you handle request validation using middleware in Express.js?
Answer: You can handle request validation using middleware in Express.js by creating custom
middleware functions that validate the request data. You can then apply these middleware functions
to the specific routes that require validation.
Example:
javascript
if (!req.body.username || !req.body.email) {
next();
};
});
Answer: You can handle JSON web tokens (JWT) in Express.js by using middleware such as
`jsonwebtoken`. This middleware allows you to generate and verify JWTs for authentication and
authorization purposes.
javascript
});
});
Answer: You can handle rate limiting in Express.js by using middleware such as `express-rate-limit`.
This middleware allows you to limit the number of requests a client can make within a certain time
period.
javascript
});
app.use(limiter);
});
95. How do you handle input sanitization and data validation in Express.js?
Answer: You can handle input sanitization and data validation in Express.js by using middleware such
as `express-validator`. This middleware provides validation and sanitization functions that can be
applied to request parameters, body, or query.
javascript
app.post('/users', [
body('username').notEmpty().trim().escape(),
body('email').isEmail().normalizeEmail(),
if (!errors.isEmpty()) {
});
96
Answer: You can handle file uploads in Express.js by using middleware such as `multer`. This
middleware allows you to handle multipart/form-data requests and store uploaded files on the
server.
javascript
const multer = require('multer');
cb(null, 'uploads/');
},
cb(null, file.originalname);
},
});
});
Answer: You can handle serving static files in Express.js by using the `express.static` middleware.
This middleware allows you to specify a directory containing static files that should be served
directly to the client.
Example:
javascript
app.use(express.static('public'));
// e.g., http://example.com/images/logo.png
Example:
javascript
});
Answer: You can handle query parameters in Express.js by accessing them through the `req.query`
object. Query parameters are the key-value pairs that follow the `?` in the URL.
Example:
javascript
});
Example:
javascript
app.listen(port, () => {
});