- Notifications
You must be signed in to change notification settings - Fork21
Devinterview-io/express-interview-questions
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
You can also find all 58 answers here 👉Devinterview.io - Express.js
Express.js is a web application framework that runs onNode.js. It simplifies the process of building web applications and APIs by providing a range of powerful features, including robust routing, middleware support, and HTTP utility methods. Thanks to its modular design, you can expand its functionality through additional libraries and Node.js modules.
Middleware: Express.js makes use of middleware functions that have access to the request-response cycle. This allows for a variety of operations such as logging, authentication, and data parsing.
Routing: The framework offers a flexible and intuitive routing system, making it easy to handle different HTTP request methods on various URLs.
Templates: Integrated support for template engines enables the dynamic rendering of HTML content.
HTTP Methods: It provides built-in methods for all HTTP requests, such as
get,post,put,delete, simplifying request handling.Error Handling: Express streamlines error management, and its middleware functions can specifically handle errors.
RESTful APIs: Its features such as request and response object chaining, along with HTTP method support, make it ideal for creating RESTful APIs.
Express.js is a web application framework specifically designed to extend the capabilities ofNode.js for web development. Node.js, on the other hand, is a cross-platform JavaScript runtime environment that allows developers to build server-side and networking applications.
Express.js accomplishes this through a layer of abstractions and a more structured approach, which Node.js, by itself, doesn't provide out of the box.
Here is the Node.js code:
// Import required modulesconstexpress=require('express');// Create an Express applicationconstapp=express();constport=3000;// Define a route and its callback functionapp.get('/',(req,res)=>{res.send('Hello World!');});// Start the serverapp.listen(port,()=>{console.log(`Server running at http://localhost:${port}/`);});
Middleware acts as a bridge between incoming HTTP requests and your Express.js application, allowing for a range of operations such as parsing request bodies, handling authentication, and even serving static files.
A middleware function in Express is ahandler invoked in sequence when an HTTP request is received. It has access to the request and response objects, as well as thenext function to trigger the next middleware in line.
Each middleware function typically follows this signature:
functionmiddlewareFunction(req,res,next){// ...middleware logicnext();// or next(err); based on whether to proceed or handle an error}
Note that thenext() call is essential to move on to the next middleware.
Registered viaapp.use(middlewareFunction), it's active for every incoming request, making it suitable for tasks like request logging or establishing cross-cutting concerns.
Operates on specific router paths and is defined usingrouter.use(middlewareFunction). It's useful for tasks related to particular sets of routes.
Recognizable via its function signature(err, req, res, next), this type of middleware specifically handles errors. In the middleware chain, it should be placed after regular middlewares and can be added usingapp.use(function(err, req, res, next) { ... }).
Express offers ready-to-use middleware for tasks like serving static files or parsing the request body.
Bysequentially callingnext() within each middleware, you form a chain, facilitating a cascade of operations for an incoming request.
Consider a multi-tiered security setup, for example, with authentication, authorization, and request validation. Only when a request passes through all three tiers will it be processed by the actual route handler.
Here is the code:
constexpress=require('express');constapp=express();// Sample middleware functionsfunctionauthenticationMiddleware(req,res,next){console.log('Authenticating...');next();}functionauthorizationMiddleware(req,res,next){console.log('Authorizing...');next();}functionrequestValidationMiddleware(req,res,next){console.log('Validating request...');next();}// The actual route handlerapp.get('/my-secured-endpoint',authenticationMiddleware,authorizationMiddleware,requestValidationMiddleware,(req,res)=>{res.send('Welcome! You are authorized.');});app.listen(3000);
To set up abasic Express.js application, follow these steps:
Create a new directory for your project and runnpm init to generate apackage.json file.
InstallExpress as a dependency using the Node Package Manager (NPM):
npm install express
In your project directory, create a main file (usually namedapp.js orindex.js) to set up the Express application.
Here is the JavaScript code:
// Import the Express moduleconstexpress=require('express');// Create an Express applicationconstapp=express();// Define a sample routeapp.get('/',(req,res)=>{res.send('Hello, World!');});// Start the serverconstport=3000;app.listen(port,()=>{console.log(`Server running on port${port}`);});
You can start your Express server using Node.js:
node app.js
For convenience, you might consider usingNodemon as a development dependency which automatically restarts the server upon file changes.
In Express.js, theapp.use() function is a powerful tool formiddleware management. It can handle HTTP requests and responses, as well as prepare data or execute processes in between.
- Global Middleware: Without a specified path, the middleware will process every request.
- Route-specific Middleware: When given a path, the middleware will only apply to the matched routes.
Body Parsing: To extract data from incoming requests, especially useful for POST and PUT requests.
constbodyParser=require('body-parser');app.use(bodyParser.json());
Handling CORS: Useful in API applications to manage cross-origin requests.
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();});
Static File Serving: For serving files like images, CSS, or client-side JavaScript.
app.use(express.static('public'));
Logging: To record request details for debugging or analytics.
app.use(function(req,res,next){console.log(`${newDate().toUTCString()}:${req.method}${req.originalUrl}`);next();});
Error Handling: To manage and report errors during request processing.
app.use(function(err,req,res,next){console.error(err);res.status(500).send('Internal Server Error');});
You canstack multiple middleware usingapp.use() in the order they need to execute. For a matched route, control can be passed to the next matching route or terminated early usingnext().
In an Express.jsweb application, you often need toserve static files such as stylesheets, client-side JavaScript, and images. You can accomplish this using theexpress.static middleware.
Theexpress.static middleware function serves static files and is typically used to serve assets like images,CSS, andclient-side JavaScript.
Here is the code example:
app.use(express.static('public'));
In this example, the folder namedpublic will be used to serve the static assets.
You can further configure the behavior of theexpress.static middleware by chaining methods.
For example, to set the cache-control header, the code looks like this:
app.use(express.static('public',{maxAge:'1d'}));
Here, the'1d' ensures that caching is enabled for a day.
If you want to serve files from a subdirectory, you can specify it when using theexpress.static middleware.
Here is the code example:
app.use('/static',express.static('public'));
This serves the files from thepublic folder but any requests for these files should start with/static.
- Images: PNG, JPEG, GIF
- Text Content: HTML, CSS, JavaScript
- Fonts
- JSON Data
Whileexpress.static is excellent forstatic assets, it's not suitable for dynamic content or data inPOST requests.
InExpress.js,app.get() andapp.post() are two of the most commonly used HTTP method middleware. The choice between them (or using both) typically depends on whether you areretrieving orsubmitting/persisting data.
app.get(): Listens for GET requests. Designed for data retrieval. Visible URLs typically trigger such requests (e.g., links or direct URL entry in the browser).
app.post(): Listens for POST requests. Intended for data submission. Typically not visible in the URL bar, commonly used for form submissions.
app.get(): Uses query parameters for data transmission, visible in the URL. Useful for simple, non-sensitive, read-only data (e.g., filtering or pagination).
app.post(): Uses request body for data transmission, which can be in various formats (e.g., JSON, form data). Ideal for more complex data, file uploads, or sensitive information.
There are cases, especially forRESTful design, where a single URL needs to handle both data retrieval and data submission.
- Resource Retrieval and Creation:
- Fetch a Form: Use
app.get()to return a form for users to fill out. - Form Submission: Use
app.post()to process and save the submitted form data.
- Fetch a Form: Use
- Complete Entity Modification: For a complete update (or replacement in REST), using
app.post()ensures that the update action is triggered via a post request, not a get request. This distiction is important to obey the RESTful principles.
Here is the JavaScript code:
constuserRecords={};// in-memory "database" for the sake of example// Handle user registration formapp.get('/users/register',(req,res)=>{res.send('Please register: <form method="POST"><input name="username"></form>');});// Process submitted registration formapp.post('/users/register',(req,res)=>{userRecords[req.body.username]=req.body;res.send('Registration complete');});
InExpress.js, you can extractURL parameters from aGET request using thereq.params object. Here's a quick look at the steps and the code example:
// Sample URL: http://example.com/users/123// Relevant Route: /users/:id// Define the endpoint/routeapp.get('/users/:id',(req,res)=>{// Retrieve the URL parameterconstuserId=req.params.id;// ... (rest of the code)});
In this example, the URL parameterid is extracted and used to fetch the corresponding user data.
For simple and straightforwardGET requests, supplying URL parameters directly works well. However, for more complex scenarios, such as parsing parameters from a URL with the help ofquerystrings or handling optional parameters,Express.js offers more advanced techniques which are outlined below:
What It Is: Additional data passed in a URL after the
?character. Example:http://example.com/resource?type=user&page=1.How to Access It: Use
req.query, an object that provides key-value pairs of the parsed query parameters.
app.get('/search',(req,res)=>{const{ q, category}=req.query;// ... (rest of the code)});
Optional Segments: URL segments enclosed in parentheses are optional and can be accessed using
req.params. Example:/book(/:title)Catch-All Segments: Captures the remainder of the URL and is useful in cases like URL rewriting. Denoted by an asterisk (
*) or double asterisk (**). Accessed usingreq.paramsas well. Example:/documents/*
Route handlers in Express.js are middleware functions designed to manage specific paths in your application.
Depending on the HTTP method and endpoint, they can perform diverse tasks, such as data retrieval from a database, view rendering, or HTTP response management.
Here is the code:
// Responds with "Hello, World!" for GET requests to the root URL (/)app.get('/',(req,res)=>{res.send('Hello, World!');});
In this example, the route handler is(req, res) => { res.send('Hello, World!'); }. It listens for GET requests on the root URL and responds with "Hello, World!".
You can associate numerous route-managingmiddleware functions to a single route. Every middleware function in the chain has to either proceed to the following function usingnext() or conclude the request-response cycle.
This allows for checks like user authentication before accessing a route.
Express.js offers specialized, highly-readable methods for the most common HTTP requests:
app.get()app.post()app.put()app.delete()app.use()
These methods streamline route handling setup.
Cross-Origin Resource Sharing (CORS) is a mechanism that allows web pages to make requests to a different domain. In Express.js, you can enable CORS using thecors package or by setting headers manually.
Install
cors:Use npm or yarn to install the
corspackage.npm install cors
Integrate with Your Express App:
Use the
app.use(cors())middleware. You can also customize CORS behavior with options.constexpress=require('express');constcors=require('cors');constapp=express();// Enable CORS for all routesapp.use(cors());// Example: Enable CORS only for a specific routeapp.get('/public-data',cors(),(req,res)=>{// ...});// Example: Customize CORS optionsconstcustomCorsOptions={origin:'https://example.com',optionsSuccessStatus:200// Some legacy browsers choke on 204};app.use(cors(customCorsOptions));
Use the following code example toset CORS headers manually in your Express app:
app.use((req,res,next)=>{res.header('Access-Control-Allow-Origin','*');res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');if(req.method==='OPTIONS'){res.header('Access-Control-Allow-Methods','GET, POST, PUT, PATCH, DELETE, OPTIONS');returnres.status(200).json({});}next();});
Make sure to place this middleware before your route definitions.
In Express.js,middleware functions are crucial for handling HTTP requests. A single request can pass through multiple middlewares before reaching its endpoint, providing opportunities for tasks like logging, data parsing, and error handling. Thenext() function is instrumental in this process, allowing for both regular middleware chaining and special error handling.
next(): A callback function that, when called within a middleware, passes control to the next middleware in the stack.next()is typically invoked to signal that a middleware has completed its tasks and that the request should move on to the next middleware.- If a middleware doesn't call
next(), the request flow can getstuck, and the subsequent middlewares won't be executed.
- Regular Flow: Invoke
next()to move the request and response objects through the middleware stack. - Error Handling: If a middleware detects an error, it can short-circuit the regular flow and jump directly to an error-handling middleware (defined with
app.use(function(err, req, res, next) {})). This is achieved by callingnext(err), whereerris the detected error.
Here is the code:
constapp=require('express')();// Sample middleware: logs the request method and URLapp.use((req,res,next)=>{console.log(`${req.method}${req.url}`);next();// Move to the next middleware});// Sample middleware: logs the current UTC timeapp.use((req,res,next)=>{console.log(newDate().toUTCString());next();// Move to the next middleware});app.listen(3000);
In this example, both middlewares callnext() to allow the request to progress to the next logging middleware and eventually to theendpoint (not shown, but would be the next in the chain).
Without thenext() calls, the request would getstuck after the first middleware.
Theexpress.Router is a powerful tool formanaging multiple route controllers. It helps in organizing routes and their handling functions into modular, self-contained groups.
Modularity: Rely on separate route modules for improved code organization, maintainability, and collaboration.
Middlewares: Like the main
expressapp, the router can also use middlewares to process incoming requests.HTTP Method Chaining: Simplifies route handling by allowing method-specific routes to be defined using method names.
Here is the Node.js code:
constexpress=require('express');constrouter=express.Router();// Logger Middlewarerouter.use((req,res,next)=>{console.log('Router-specific Request Time:',Date.now());next();});// "GET" method routerouter.get('/',(req,res)=>{res.send('Router Home Page');});// "POST" method routerouter.post('/',(req,res)=>{res.send('Router Home Page - POST Request');});module.exports=router;
In this example, we:
- Utilize the built-in
express.Router. - Attach a general-purpose middleware and two different HTTP method-specific routes.
- The router is then integrated into the main
expressapp using:
constapp=express();constrouter=require('./myRouterModule');app.use('/routerExample',router);
Here,app.use('/routerExample', router); assigns all routes defined in the router to/routerExample.
Handling 404 errors in Express is essential for capturing and responding to requests for non-existent resources. You typically use bothmiddleware andHTTP response mechanisms for this purpose.
- Use
app.useat the end of the middleware chain to capture unresolved routes. - Invoke the middleware with
next()and anErrorobject to forward to the error-handling middleware.
Here is the Node.js code example:
app.use((req,res,next)=>{consterr=newError(`Not Found:${req.originalUrl}`);err.status=404;next(err);});
- Define an error-handling middleware withfour arguments. The first one being the
errorobject. - Check the error's status and respond accordingly. If it's a 404, handle it as a not-found error; otherwise, handle it as a server error.
Here is the Node.js code:
app.use((err,req,res,next)=>{conststatus=err.status||500;constmessage=err.message||"Internal Server Error";res.status(status).send(message);});
Here is the complete Node.js application:
constexpress=require('express');constapp=express();constport=3000;// Sample router for demonstrationconstusersRouter=express.Router();usersRouter.get('/profile',(req,res)=>{res.send('User Profile');});app.use('/users',usersRouter);// Capture 404sapp.use((req,res,next)=>{consterr=newError(`Not Found:${req.originalUrl}`);err.status=404;next(err);});// Error-handling middlewareapp.use((err,req,res,next)=>{conststatus=err.status||500;constmessage=err.message||"Internal Server Error";res.status(status).send(message);});app.listen(port,()=>{console.log(`Example app listening at http://localhost:${port}`);});
In Express.js,req.query is used to accessGET request parameters, whilereq.params is used to capture parameters defined in theURL path.
Express.js usesapp.get() and similar functions to handle different types of HTTP requests.
- app.get('/users/:id'): Matches GET requests to
/users/123where123is the:idparameter in the path.
- req.query: Utilized to extract query string parameters from the request URL. Example: For the URL
/route?id=123, usereq.query.idto obtain123. - req.params: Used to retrieve parameters from the request URL path. For the route
/users/:id, usereq.params.idto capture the ID, such as for/users/123.
Here is the Express.js server setup:
constexpress=require('express');constapp=express();constport=3000;// Endpoint to capture query string parameterapp.get('/query',(req,res)=>{console.log(req.query);res.send('Received your query param!');});// Endpoint to capture URL parameterapp.get('/user/:id',(req,res)=>{console.log(req.params);res.send('Received your URL param!');});app.listen(port,()=>console.log(`Listening on port${port}!`));
In an Express.js application,req.body is a property of theHTTP request object that contains data submitted through an HTTP POST request.
The POST request might originate from an HTML form, a client-side JavaScript code, or another API client. The data inreq.body is typically structured as a JSON object or a URL-encoded form.
Theexpress.json() andexpress.urlencoded() middleware parse incomingRequest objects before passing them on. These middlewares populatereq.body with the parsed JSON and URL-encoded data, respectively.
Here is an example of how you might set up body parsing in an Express app:
constexpress=require('express');constapp=express();// Parse JSON and URL-encoded data into req.bodyapp.use(express.json());app.use(express.urlencoded({extended:true}));
Once the body parsing middleware is in place, you can access the parsed data in yourroute handling functions:
- POST orPUT Requests: When a client submits a POST or PUT request with a JSON payload in the request body, you can access this data through
req.body.
Here is an example:
Client-side #"auto" data-snippet-clipboard-copy-content="fetch('/example-route', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' })});">
fetch('/example-route',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({key:'value'})});
Server-side Express route handler:
app.post('/example-route',(req,res)=>{console.log(req.body);// Outputs: { key: 'value' }});
- HTML Forms: When a form is submitted using
<form>withactionpointing to your Express route andmethodas POST or PUT, and the form fields are input elements within the form,req.bodywill contain these form field values.
Here is an example:
HTML form:
<formaction="/form-endpoint"method="POST"><inputtype="text"name="username"/><inputtype="password"name="password"/><buttontype="submit">Submit</button></form>
Express route:
app.post('/form-endpoint',(req,res)=>{console.log(req.body.username,req.body.password);});
A modern technique for sending form data usingfetch is by setting theContent-Type header to'application/x-www-form-urlencoded' and using theURLSearchParams object:
fetch('/form-endpoint',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:newURLSearchParams({username:'user',password:'pass'})});
- Custom Parsers: While Express provides built-in body parsers for JSON and URL-encoded data, you might receive data in another format. In such cases, you can create custom middleware to parse and shape the data as needed. This middleware should populate
req.body.
In Express.js,middlewares allow you to handle HTTP requests. Here, you will learn how to create a simplelogging middleware that records the request method and URL.
First, install Express via npm, and set up yourapp.js file:
constexpress=require('express');constapp=express();
Define a logging function that extracts the request method and URL, and then useapp.use() to mount it as middleware.
// Logging MiddlewareconstlogRequest=(req,res,next)=>{console.log(`Received${req.method} request for:${req.url}`);next();// Call next to proceed to the next middleware};// Mount the middleware for all routesapp.use(logRequest);
Useapp.get() to handle GET requests, andapp.listen() to start the server.
// Sample routeapp.get('/',(req,res)=>{res.send('Hello World');});// Start the serverapp.listen(3000,()=>{console.log('Server is running on port 3000');});
When you visithttp://localhost:3000/ in your browser and check the server console, you should see the request being logged.
Explore all 58 answers here 👉Devinterview.io - Express.js

About
🟣 Express.js interview questions and answers to help you prepare for your next technical interview in 2025.
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.