Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🟣 Express.js interview questions and answers to help you prepare for your next technical interview in 2025.

NotificationsYou must be signed in to change notification settings

Devinterview-io/express-interview-questions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 

Repository files navigation

web-and-mobile-development

You can also find all 58 answers here 👉Devinterview.io - Express.js


1. What isExpress.js, and how does it relate toNode.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.

Key Features

  • 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 asget,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.

Relationship with Node.js

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.

Code Example: Basic Express Server

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}/`);});

2. Explain the concept ofmiddleware inExpress.js.

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.

Middleware Functions

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.

Types of Middleware

Application-Level 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.

Router-Level Middleware

Operates on specific router paths and is defined usingrouter.use(middlewareFunction). It's useful for tasks related to particular sets of routes.

Error-Handling Middleware

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) { ... }).

Built-In Middleware

Express offers ready-to-use middleware for tasks like serving static files or parsing the request body.

Middleware Chaining

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.

Code Example: Middleware Chaining

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);

3. How would you set up a basicExpress.js application?

To set up abasic Express.js application, follow these steps:

1. Initialize the Project

Create a new directory for your project and runnpm init to generate apackage.json file.

2. Install Dependencies

InstallExpress as a dependency using the Node Package Manager (NPM):

npm install express

3. Create the Application

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}`);});

4. Run the Application

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.

4. What is the purpose of theapp.use() function?

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.

Key Functions

  • 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.

Common Use-Cases

  • 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');});

Chaining Middleware

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().

5. How do you servestatic files usingExpress.js?

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.

Middleware for Serving Static Files

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.

Additional Configuration with Method Chaining

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.

Using a Subdirectory

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.

Whatexpress.static Serves

  • Images: PNG, JPEG, GIF
  • Text Content: HTML, CSS, JavaScript
  • Fonts
  • JSON Data

Not for dynamic content

Whileexpress.static is excellent forstatic assets, it's not suitable for dynamic content or data inPOST requests.

6. Discuss the difference betweenapp.get() andapp.post() inExpress.js.

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.

Key Distinctions

HTTP Verbs: External Visibility

  • 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.

Data Transmission

  • 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.

Using Bothapp.get() andapp.post() for the Same Route

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: Useapp.get() to return a form for users to fill out.
    • Form Submission: Useapp.post() to process and save the submitted form data.
  • Complete Entity Modification: For a complete update (or replacement in REST), usingapp.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.

Code Example: Using bothapp.get() andapp.post() for a single route

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');});

7. How do you retrieve theURL parameters from aGET request inExpress.js?

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:

Code Example: Retrieving URL Parameters

// 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.

Additional Steps for Complex GET Requests

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:

Parsing Query Parameters

  • 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: Usereq.query, an object that provides key-value pairs of the parsed query parameters.

Code Example: Parsing Query Parameters

app.get('/search',(req,res)=>{const{ q, category}=req.query;// ... (rest of the code)});

Optional and Catch-All Segments

  • Optional Segments: URL segments enclosed in parentheses are optional and can be accessed usingreq.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.params as well. Example:/documents/*


8. What areroute handlers, and how would you implement them?

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.

Code Example: Setting Up a Simple Route Handler

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!".

What Are Route-Handler Chains?

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.

HTTP Method Convenience Methods

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.

9. How do you enableCORS in anExpress.js application?

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.

Using thecors Package

  1. Installcors:

    Use npm or yarn to install thecors package.

    npm install cors
  2. Integrate with Your Express App:

    Use theapp.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));

Manual CORS Setup

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.

10. Explain the use ofnext() inExpress.js middleware.

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.

What isnext()?

  • 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 callnext(), the request flow can getstuck, and the subsequent middlewares won't be executed.

Use-Cases

  1. Regular Flow: Invokenext() to move the request and response objects through the middleware stack.
  2. Error Handling: If a middleware detects an error, it can short-circuit the regular flow and jump directly to an error-handling middleware (defined withapp.use(function(err, req, res, next) {})). This is achieved by callingnext(err), whereerr is the detected error.

Code Example: Logging Middleware

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.

11. What is the role of theexpress.Router class?

Theexpress.Router is a powerful tool formanaging multiple route controllers. It helps in organizing routes and their handling functions into modular, self-contained groups.

Key Features

  • Modularity: Rely on separate route modules for improved code organization, maintainability, and collaboration.

  • Middlewares: Like the mainexpress app, 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.

Example: Middleware and Route Handling

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-inexpress.Router.
  • Attach a general-purpose middleware and two different HTTP method-specific routes.
  • The router is then integrated into the mainexpress app using:
constapp=express();constrouter=require('./myRouterModule');app.use('/routerExample',router);

Here,app.use('/routerExample', router); assigns all routes defined in the router to/routerExample.

12. How do you handle404 errors inExpress.js?

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.

Middleware for 404s

  1. Useapp.use at the end of the middleware chain to capture unresolved routes.
  2. Invoke the middleware withnext() and anError object 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);});

Error-Handling Middleware for 404s and Other Errors

  1. Define an error-handling middleware withfour arguments. The first one being theerror object.
  2. 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);});

Full Example:

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}`);});

13. What are the differences betweenreq.query andreq.params?

In Express.js,req.query is used to accessGET request parameters, whilereq.params is used to capture parameters defined in theURL path.

Understanding Express.js Routing

Express.js usesapp.get() and similar functions to handle different types of HTTP requests.

  • app.get('/users/:id'): Matches GET requests to/users/123 where123 is the:id parameter in the path.

Accessing Request Data

  • req.query: Utilized to extract query string parameters from the request URL. Example: For the URL/route?id=123, usereq.query.id to obtain123.
  • req.params: Used to retrieve parameters from the request URL path. For the route/users/:id, usereq.params.id to capture the ID, such as for/users/123.

Code Example: Request Data

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}!`));

14. Describe the purpose ofreq.body and how you would access it.

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.

Middleware and Parsing Request Body

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}));

Accessingreq.body Data

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 throughreq.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> withaction pointing to your Express route andmethod as POST or PUT, and the form fields are input elements within the form,req.body will 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 populatereq.body.

15. How do you create amiddleware that logs therequest method andURL for every request?

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.

Setting Up the Express App

First, install Express via npm, and set up yourapp.js file:

constexpress=require('express');constapp=express();

Creating the Logging Middleware

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);

Testing the Setup

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


web-and-mobile-development


[8]ページ先頭

©2009-2025 Movatter.jp