└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # Top 58 Express.js Interview Questions in 2025. 2 | 3 |
4 |

5 | 6 | web-and-mobile-development 7 | 8 |

9 | 10 | #### You can also find all 58 answers here 👉 [Devinterview.io - Express.js](https://devinterview.io/questions/web-and-mobile-development/express-interview-questions) 11 | 12 |
13 | 14 | ## 1. What is _Express.js_, and how does it relate to _Node.js_? 15 | 16 | **Express.js** is a web application framework that runs on **Node.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. 17 | 18 | ### Key Features 19 | 20 | - **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. 21 | 22 | - **Routing**: The framework offers a flexible and intuitive routing system, making it easy to handle different HTTP request methods on various URLs. 23 | 24 | - **Templates**: Integrated support for template engines enables the dynamic rendering of HTML content. 25 | 26 | - **HTTP Methods**: It provides built-in methods for all HTTP requests, such as `get`, `post`, `put`, `delete`, simplifying request handling. 27 | 28 | - **Error Handling**: Express streamlines error management, and its middleware functions can specifically handle errors. 29 | 30 | - **RESTful APIs**: Its features such as request and response object chaining, along with HTTP method support, make it ideal for creating RESTful APIs. 31 | 32 | ### Relationship with Node.js 33 | 34 | Express.js is a web application framework specifically designed to extend the capabilities of **Node.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. 35 | 36 | 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. 37 | 38 | ### Code Example: Basic Express Server 39 | 40 | Here is the Node.js code: 41 | 42 | ```javascript 43 | // Import required modules 44 | const express = require('express'); 45 | 46 | // Create an Express application 47 | const app = express(); 48 | const port = 3000; 49 | 50 | // Define a route and its callback function 51 | app.get('/', (req, res) => { 52 | res.send('Hello World!'); 53 | }); 54 | 55 | // Start the server 56 | app.listen(port, () => { 57 | console.log(`Server running at http://localhost:${port}/`); 58 | }); 59 | ``` 60 |
61 | 62 | ## 2. Explain the concept of _middleware_ in _Express.js_. 63 | 64 | **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. 65 | 66 | ### Middleware Functions 67 | 68 | A middleware function in Express is a **handler invoked in sequence** when an HTTP request is received. It has access to the request and response objects, as well as the `next` function to trigger the next middleware in line. 69 | 70 | Each middleware function typically follows this signature: 71 | 72 | ```javascript 73 | function middlewareFunction(req, res, next) { 74 | // ...middleware logic 75 | next(); // or next(err); based on whether to proceed or handle an error 76 | } 77 | ``` 78 | 79 | Note that the `next()` call is essential to move on to the next middleware. 80 | 81 | ### Types of Middleware 82 | 83 | #### Application-Level Middleware 84 | 85 | Registered via `app.use(middlewareFunction)`, it's active for every incoming request, making it suitable for tasks like request logging or establishing cross-cutting concerns. 86 | 87 | #### Router-Level Middleware 88 | 89 | Operates on specific router paths and is defined using `router.use(middlewareFunction)`. It's useful for tasks related to particular sets of routes. 90 | 91 | #### Error-Handling Middleware 92 | 93 | 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 using `app.use(function(err, req, res, next) { ... })`. 94 | 95 | #### Built-In Middleware 96 | 97 | Express offers ready-to-use middleware for tasks like serving static files or parsing the request body. 98 | 99 | ### Middleware Chaining 100 | 101 | By **sequentially** calling `next()` within each middleware, you form a chain, facilitating a cascade of operations for an incoming request. 102 | 103 | 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. 104 | 105 | ### Code Example: Middleware Chaining 106 | 107 | Here is the code: 108 | 109 | ```javascript 110 | const express = require('express'); 111 | const app = express(); 112 | 113 | // Sample middleware functions 114 | function authenticationMiddleware(req, res, next) { 115 | console.log('Authenticating...'); 116 | next(); 117 | } 118 | 119 | function authorizationMiddleware(req, res, next) { 120 | console.log('Authorizing...'); 121 | next(); 122 | } 123 | 124 | function requestValidationMiddleware(req, res, next) { 125 | console.log('Validating request...'); 126 | next(); 127 | } 128 | 129 | // The actual route handler 130 | app.get('/my-secured-endpoint', authenticationMiddleware, authorizationMiddleware, requestValidationMiddleware, (req, res) => { 131 | res.send('Welcome! You are authorized.'); 132 | }); 133 | 134 | app.listen(3000); 135 | ``` 136 |
137 | 138 | ## 3. How would you set up a basic _Express.js_ application? 139 | 140 | To set up a **basic Express.js** application, follow these steps: 141 | 142 | ### 1. Initialize the Project 143 | 144 | Create a new directory for your project and run `npm init` to generate a `package.json` file. 145 | 146 | ### 2. Install Dependencies 147 | 148 | Install **Express** as a dependency using the Node Package Manager (NPM): 149 | ```bash 150 | npm install express 151 | ``` 152 | 153 | ### 3. Create the Application 154 | 155 | In your project directory, create a main file (usually named `app.js` or `index.js`) to set up the Express application. 156 | 157 | Here is the JavaScript code: 158 | 159 | ```javascript 160 | // Import the Express module 161 | const express = require('express'); 162 | 163 | // Create an Express application 164 | const app = express(); 165 | 166 | // Define a sample route 167 | app.get('/', (req, res) => { 168 | res.send('Hello, World!'); 169 | }); 170 | 171 | // Start the server 172 | const port = 3000; 173 | app.listen(port, () => { 174 | console.log(`Server running on port ${port}`); 175 | }); 176 | ``` 177 | 178 | ### 4. Run the Application 179 | 180 | You can start your Express server using Node.js: 181 | ```bash 182 | node app.js 183 | ``` 184 | 185 | For convenience, you might consider using **Nodemon** as a development dependency which automatically restarts the server upon file changes. 186 |
187 | 188 | ## 4. What is the purpose of the `app.use()` function? 189 | 190 | In Express.js, the `app.use()` function is a powerful tool for **middleware management**. It can handle HTTP requests and responses, as well as prepare data or execute processes in between. 191 | 192 | ### Key Functions 193 | 194 | - **Global Middleware**: Without a specified path, the middleware will process every request. 195 | - **Route-specific Middleware**: When given a path, the middleware will only apply to the matched routes. 196 | 197 | ### Common Use-Cases 198 | 199 | - **Body Parsing**: To extract data from incoming requests, especially useful for POST and PUT requests. 200 | 201 | ```javascript 202 | const bodyParser = require('body-parser'); 203 | app.use(bodyParser.json()); 204 | ``` 205 | 206 | - **Handling CORS**: Useful in API applications to manage cross-origin requests. 207 | 208 | ```javascript 209 | app.use(function(req, res, next) { 210 | res.header("Access-Control-Allow-Origin", "*"); 211 | res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 212 | next(); 213 | }); 214 | ``` 215 | 216 | - **Static File Serving**: For serving files like images, CSS, or client-side JavaScript. 217 | 218 | ```javascript 219 | app.use(express.static('public')); 220 | ``` 221 | 222 | - **Logging**: To record request details for debugging or analytics. 223 | 224 | ```javascript 225 | app.use(function(req, res, next) { 226 | console.log(`${new Date().toUTCString()}: ${req.method} ${req.originalUrl}`); 227 | next(); 228 | }); 229 | ``` 230 | 231 | - **Error Handling**: To manage and report errors during request processing. 232 | 233 | ```javascript 234 | app.use(function(err, req, res, next) { 235 | console.error(err); 236 | res.status(500).send('Internal Server Error'); 237 | }); 238 | ``` 239 | 240 | ### Chaining Middleware 241 | 242 | You can **stack multiple middleware** using `app.use()` in the order they need to execute. For a matched route, control can be passed to the next matching route or terminated early using `next()`. 243 |
244 | 245 | ## 5. How do you serve _static files_ using _Express.js_? 246 | 247 | In an Express.js **web application**, you often need to **serve static files** such as stylesheets, client-side JavaScript, and images. You can accomplish this using the `express.static` middleware. 248 | 249 | ### Middleware for Serving Static Files 250 | 251 | The `express.static` middleware function serves static files and is typically used to serve assets like images, **CSS**, and **client-side JavaScript**. 252 | 253 | Here is the code example: 254 | 255 | ```javascript 256 | app.use(express.static('public')); 257 | ``` 258 | 259 | In this example, the folder named `public` will be used to serve the static assets. 260 | 261 | ### Additional Configuration with Method Chaining 262 | 263 | You can further configure the behavior of the `express.static` middleware by chaining methods. 264 | 265 | For example, to set the cache-control header, the code looks like this: 266 | 267 | ```javascript 268 | app.use(express.static('public', { 269 | maxAge: '1d' 270 | })); 271 | ``` 272 | 273 | Here, the `'1d'` ensures that caching is enabled for a day. 274 | 275 | ### Using a Subdirectory 276 | 277 | If you want to serve files from a subdirectory, you can specify it when using the `express.static` middleware. 278 | 279 | Here is the code example: 280 | 281 | ```javascript 282 | app.use('/static', express.static('public')); 283 | ``` 284 | 285 | This serves the files from the `public` folder but any requests for these files should start with `/static`. 286 | 287 | ### What `express.static` Serves 288 | 289 | - **Images**: PNG, JPEG, GIF 290 | - **Text Content**: HTML, CSS, JavaScript 291 | - **Fonts** 292 | - **JSON Data** 293 | 294 | #### Not for dynamic content 295 | 296 | While `express.static` is excellent for **static assets**, it's not suitable for dynamic content or data in **POST** requests. 297 |
298 | 299 | ## 6. Discuss the difference between `app.get()` and `app.post()` in _Express.js_. 300 | 301 | In **Express.js**, `app.get()` and `app.post()` are two of the most commonly used HTTP method middleware. The choice between them (or using both) typically depends on whether you are **retrieving** or **submitting/persisting** data. 302 | 303 | ### Key Distinctions 304 | 305 | #### HTTP Verbs: External Visibility 306 | 307 | - **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). 308 | 309 | - **app.post()**: Listens for POST requests. Intended for data submission. Typically not visible in the URL bar, commonly used for form submissions. 310 | 311 | #### Data Transmission 312 | 313 | - **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). 314 | 315 | - **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. 316 | 317 | ### Using Both `app.get()` and `app.post()` for the Same Route 318 | 319 | There are cases, especially for **RESTful** design, where a single URL needs to handle both data retrieval and data submission. 320 | 321 | - **Resource Retrieval and Creation**: 322 | - **Fetch a Form**: Use `app.get()` to return a form for users to fill out. 323 | - **Form Submission**: Use `app.post()` to process and save the submitted form data. 324 | - **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. 325 | 326 | ### Code Example: Using both `app.get()` and `app.post()` for a single route 327 | 328 | Here is the JavaScript code: 329 | ```javascript 330 | const userRecords = {}; // in-memory "database" for the sake of example 331 | 332 | // Handle user registration form 333 | app.get('/users/register', (req, res) => { 334 | res.send('Please register:
'); 335 | }); 336 | 337 | // Process submitted registration form 338 | app.post('/users/register', (req, res) => { 339 | userRecords[req.body.username] = req.body; 340 | res.send('Registration complete'); 341 | }); 342 | ``` 343 |
344 | 345 | ## 7. How do you retrieve the _URL parameters_ from a _GET request_ in _Express.js_? 346 | 347 | In **Express.js**, you can extract **URL parameters** from a **GET** request using the `req.params` object. Here's a quick look at the steps and the code example: 348 | 349 | ### Code Example: Retrieving URL Parameters 350 | 351 | ```javascript 352 | // Sample URL: http://example.com/users/123 353 | // Relevant Route: /users/:id 354 | 355 | // Define the endpoint/route 356 | app.get('/users/:id', (req, res) => { 357 | // Retrieve the URL parameter 358 | const userId = req.params.id; 359 | // ... (rest of the code) 360 | }); 361 | ``` 362 | 363 | In this example, the URL parameter `id` is extracted and used to fetch the corresponding user data. 364 | 365 | ### Additional Steps for Complex GET Requests 366 | 367 | For simple and straightforward **GET** requests, supplying URL parameters directly works well. However, for more complex scenarios, such as parsing parameters from a URL with the help of `querystrings` or handling optional parameters, **Express.js** offers more advanced techniques which are outlined below: 368 | 369 | #### Parsing Query Parameters 370 | 371 | - **What It Is**: Additional data passed in a URL after the `?` character. Example: `http://example.com/resource?type=user&page=1`. 372 | 373 | - **How to Access It**: Use `req.query`, an object that provides key-value pairs of the parsed query parameters. 374 | 375 | #### Code Example: Parsing Query Parameters 376 | 377 | ```javascript 378 | app.get('/search', (req, res) => { 379 | const { q, category } = req.query; 380 | // ... (rest of the code) 381 | }); 382 | ``` 383 | 384 | #### Optional and Catch-All Segments 385 | 386 | - **Optional Segments**: URL segments enclosed in parentheses are optional and can be accessed using `req.params`. Example: `/book(/:title)` 387 | 388 | - **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 using `req.params` as well. Example: `/documents/*` 389 |
390 | 391 | ## 8. What are _route handlers_, and how would you implement them? 392 | 393 | **Route handlers** in Express.js are middleware functions designed to manage specific paths in your application. 394 | 395 | 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. 396 | 397 | ### Code Example: Setting Up a Simple Route Handler 398 | 399 | Here is the code: 400 | 401 | ```javascript 402 | // Responds with "Hello, World!" for GET requests to the root URL (/) 403 | app.get('/', (req, res) => { 404 | res.send('Hello, World!'); 405 | }); 406 | ``` 407 | 408 | 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!". 409 | 410 | ### What Are Route-Handler Chains? 411 | 412 | You can associate numerous route-managing **middleware functions** to a single route. Every middleware function in the chain has to either proceed to the following function using `next()` or conclude the request-response cycle. 413 | 414 | This allows for checks like user authentication before accessing a route. 415 | 416 | ### HTTP Method Convenience Methods 417 | 418 | Express.js offers specialized, highly-readable methods for the most common HTTP requests: 419 | 420 | - `app.get()` 421 | - `app.post()` 422 | - `app.put()` 423 | - `app.delete()` 424 | - `app.use()` 425 | 426 | These methods streamline route handling setup. 427 |
428 | 429 | ## 9. How do you enable _CORS_ in an _Express.js_ application? 430 | 431 | **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 the `cors` package or by setting headers manually. 432 | 433 | ### Using the `cors` Package 434 | 435 | 1. **Install `cors`**: 436 | 437 | Use npm or yarn to install the `cors` package. 438 | 439 | ```bash 440 | npm install cors 441 | ``` 442 | 443 | 2. **Integrate with Your Express App**: 444 | 445 | Use the `app.use(cors())` middleware. You can also customize CORS behavior with options. 446 | 447 | ```javascript 448 | const express = require('express'); 449 | const cors = require('cors'); 450 | const app = express(); 451 | 452 | // Enable CORS for all routes 453 | app.use(cors()); 454 | 455 | // Example: Enable CORS only for a specific route 456 | app.get('/public-data', cors(), (req, res) => { 457 | // ... 458 | }); 459 | 460 | // Example: Customize CORS options 461 | const customCorsOptions = { 462 | origin: 'https://example.com', 463 | optionsSuccessStatus: 200 // Some legacy browsers choke on 204 464 | }; 465 | 466 | app.use(cors(customCorsOptions)); 467 | ``` 468 | 469 | ### Manual CORS Setup 470 | 471 | Use the following code example to **set CORS headers manually** in your Express app: 472 | 473 | ```javascript 474 | app.use((req, res, next) => { 475 | res.header('Access-Control-Allow-Origin', '*'); 476 | res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); 477 | if (req.method === 'OPTIONS') { 478 | res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS'); 479 | return res.status(200).json({}); 480 | } 481 | next(); 482 | }); 483 | ``` 484 | 485 | Make sure to place this middleware before your route definitions. 486 |
487 | 488 | ## 10. Explain the use of `next()` in _Express.js middleware_. 489 | 490 | 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. The `next()` function is instrumental in this process, allowing for both regular middleware chaining and special error handling. 491 | 492 | ### What is `next()`? 493 | 494 | - `next()`: A callback function that, when called within a middleware, passes control to the next middleware in the stack. 495 | - `next()` is typically invoked to signal that a middleware has completed its tasks and that the request should move on to the next middleware. 496 | - If a middleware doesn't call `next()`, the request flow can get **stuck**, and the subsequent middlewares won't be executed. 497 | 498 | ### Use-Cases 499 | 500 | 1. **Regular Flow**: Invoke `next()` to move the request and response objects through the middleware stack. 501 | 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 with `app.use(function(err, req, res, next) {})`). This is achieved by calling `next(err)`, where `err` is the detected error. 502 | 503 | ### Code Example: Logging Middleware 504 | 505 | Here is the code: 506 | 507 | ```javascript 508 | const app = require('express')(); 509 | 510 | // Sample middleware: logs the request method and URL 511 | app.use((req, res, next) => { 512 | console.log(`${req.method} ${req.url}`); 513 | next(); // Move to the next middleware 514 | }); 515 | 516 | // Sample middleware: logs the current UTC time 517 | app.use((req, res, next) => { 518 | console.log(new Date().toUTCString()); 519 | next(); // Move to the next middleware 520 | }); 521 | 522 | app.listen(3000); 523 | ``` 524 | 525 | In this example, both middlewares call `next()` to allow the request to progress to the next logging middleware and eventually to the **endpoint** (not shown, but would be the next in the chain). 526 | 527 | Without the `next()` calls, the request would get **stuck** after the first middleware. 528 |
529 | 530 | ## 11. What is the role of the `express.Router` class? 531 | 532 | The `express.Router` is a powerful tool for **managing multiple route controllers**. It helps in organizing routes and their handling functions into modular, self-contained groups. 533 | 534 | ### Key Features 535 | 536 | - **Modularity**: Rely on separate route modules for improved code organization, maintainability, and collaboration. 537 | 538 | - **Middlewares**: Like the main `express` app, the router can also use middlewares to process incoming requests. 539 | 540 | - **HTTP Method Chaining**: Simplifies route handling by allowing method-specific routes to be defined using method names. 541 | 542 | #### Example: Middleware and Route Handling 543 | 544 | Here is the Node.js code: 545 | 546 | ```javascript 547 | const express = require('express'); 548 | const router = express.Router(); 549 | 550 | // Logger Middleware 551 | router.use((req, res, next) => { 552 | console.log('Router-specific Request Time:', Date.now()); 553 | next(); 554 | }); 555 | 556 | // "GET" method route 557 | router.get('/', (req, res) => { 558 | res.send('Router Home Page'); 559 | }); 560 | 561 | // "POST" method route 562 | router.post('/', (req, res) => { 563 | res.send('Router Home Page - POST Request'); 564 | }); 565 | 566 | module.exports = router; 567 | ``` 568 | 569 | In this example, we: 570 | 571 | - Utilize the built-in `express.Router`. 572 | - Attach a general-purpose middleware and two different HTTP method-specific routes. 573 | - The router is then integrated into the main `express` app using: 574 | 575 | ```javascript 576 | const app = express(); 577 | const router = require('./myRouterModule'); 578 | 579 | app.use('/routerExample', router); 580 | ``` 581 | 582 | Here, `app.use('/routerExample', router);` assigns all routes defined in the router to `/routerExample`. 583 |
584 | 585 | ## 12. How do you handle _404 errors_ in _Express.js_? 586 | 587 | **Handling 404 errors** in Express is essential for capturing and responding to requests for non-existent resources. You typically use both **middleware** and **HTTP response** mechanisms for this purpose. 588 | 589 | ### Middleware for 404s 590 | 591 | 1. Use `app.use` at the end of the middleware chain to capture unresolved routes. 592 | 2. Invoke the middleware with `next()` and an `Error` object to forward to the error-handling middleware. 593 | 594 | Here is the Node.js code example: 595 | 596 | ```javascript 597 | app.use((req, res, next) => { 598 | const err = new Error(`Not Found: ${req.originalUrl}`); 599 | err.status = 404; 600 | next(err); 601 | }); 602 | ``` 603 | 604 | ### Error-Handling Middleware for 404s and Other Errors 605 | 606 | 1. Define an error-handling middleware with **four** arguments. The first one being the `error` object. 607 | 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. 608 | 609 | Here is the Node.js code: 610 | 611 | ```javascript 612 | app.use((err, req, res, next) => { 613 | const status = err.status || 500; 614 | const message = err.message || "Internal Server Error"; 615 | 616 | res.status(status).send(message); 617 | }); 618 | ``` 619 | 620 | ### Full Example: 621 | 622 | Here is the complete Node.js application: 623 | 624 | ```javascript 625 | const express = require('express'); 626 | const app = express(); 627 | const port = 3000; 628 | 629 | // Sample router for demonstration 630 | const usersRouter = express.Router(); 631 | usersRouter.get('/profile', (req, res) => { 632 | res.send('User Profile'); 633 | }); 634 | app.use('/users', usersRouter); 635 | 636 | // Capture 404s 637 | app.use((req, res, next) => { 638 | const err = new Error(`Not Found: ${req.originalUrl}`); 639 | err.status = 404; 640 | next(err); 641 | }); 642 | 643 | // Error-handling middleware 644 | app.use((err, req, res, next) => { 645 | const status = err.status || 500; 646 | const message = err.message || "Internal Server Error"; 647 | res.status(status).send(message); 648 | }); 649 | 650 | app.listen(port, () => { 651 | console.log(`Example app listening at http://localhost:${port}`); 652 | }); 653 | ``` 654 |
655 | 656 | ## 13. What are the differences between `req.query` and `req.params`? 657 | 658 | In Express.js, `req.query` is used to access **GET** request parameters, while `req.params` is used to capture parameters defined in the **URL path**. 659 | 660 | ### Understanding Express.js Routing 661 | 662 | Express.js uses **app.get()** and similar functions to handle different types of HTTP requests. 663 | 664 | - **app.get('/users/:id')**: Matches GET requests to `/users/123` where `123` is the `:id` parameter in the path. 665 | 666 | ### Accessing Request Data 667 | 668 | - **req.query**: Utilized to extract query string parameters from the request URL. Example: For the URL `/route?id=123`, use `req.query.id` to obtain `123`. 669 | - **req.params**: Used to retrieve parameters from the request URL path. For the route `/users/:id`, use `req.params.id` to capture the ID, such as for `/users/123`. 670 | 671 | ### Code Example: Request Data 672 | 673 | Here is the Express.js server setup: 674 | 675 | ```javascript 676 | const express = require('express'); 677 | const app = express(); 678 | const port = 3000; 679 | 680 | // Endpoint to capture query string parameter 681 | app.get('/query', (req, res) => { 682 | console.log(req.query); 683 | res.send('Received your query param!'); 684 | }); 685 | 686 | // Endpoint to capture URL parameter 687 | app.get('/user/:id', (req, res) => { 688 | console.log(req.params); 689 | res.send('Received your URL param!'); 690 | }); 691 | 692 | app.listen(port, () => console.log(`Listening on port ${port}!`)); 693 | ``` 694 |
695 | 696 | ## 14. Describe the purpose of `req.body` and how you would access it. 697 | 698 | In an Express.js application, `req.body` is a property of the **HTTP request object** that contains data submitted through an HTTP POST request. 699 | 700 | The POST request might originate from an HTML form, a client-side JavaScript code, or another API client. The data in `req.body` is typically structured as a JSON object or a URL-encoded form. 701 | 702 | ### Middleware and Parsing Request Body 703 | 704 | The `express.json()` and `express.urlencoded()` middleware parse incoming `Request` objects before passing them on. These middlewares populate `req.body` with the parsed JSON and URL-encoded data, respectively. 705 | 706 | Here is an example of how you might set up body parsing in an Express app: 707 | 708 | ```javascript 709 | const express = require('express'); 710 | const app = express(); 711 | 712 | // Parse JSON and URL-encoded data into req.body 713 | app.use(express.json()); 714 | app.use(express.urlencoded({ extended: true })); 715 | ``` 716 | 717 | ### Accessing `req.body` Data 718 | 719 | Once the body parsing middleware is in place, you can access the parsed data in your **route handling** functions: 720 | 721 | - **POST** or **PUT** 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`. 722 | 723 | Here is an example: 724 | 725 | Client-side JavaScript: 726 | 727 | ```javascript 728 | fetch('/example-route', { 729 | method: 'POST', 730 | headers: { 731 | 'Content-Type': 'application/json' 732 | }, 733 | body: JSON.stringify({ key: 'value' }) 734 | }); 735 | ``` 736 | 737 | Server-side Express route handler: 738 | 739 | ```javascript 740 | app.post('/example-route', (req, res) => { 741 | console.log(req.body); // Outputs: { key: 'value' } 742 | }); 743 | ``` 744 | 745 | - **HTML Forms**: When a form is submitted using `
` with `action` pointing to your Express route and `method` as POST or PUT, and the form fields are input elements within the form, `req.body` will contain these form field values. 746 | 747 | Here is an example: 748 | 749 | HTML form: 750 | 751 | ```html 752 | 753 | 754 | 755 | 756 |
757 | ``` 758 | 759 | Express route: 760 | 761 | ```javascript 762 | app.post('/form-endpoint', (req, res) => { 763 | console.log(req.body.username, req.body.password); 764 | }); 765 | ``` 766 | 767 | A modern technique for sending form data using `fetch` is by setting the `Content-Type` header to `'application/x-www-form-urlencoded'` and using the `URLSearchParams` object: 768 | 769 | ```javascript 770 | fetch('/form-endpoint', { 771 | method: 'POST', 772 | headers: { 773 | 'Content-Type': 'application/x-www-form-urlencoded' 774 | }, 775 | body: new URLSearchParams({ username: 'user', password: 'pass' }) 776 | }); 777 | ``` 778 | 779 | - **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`. 780 |
781 | 782 | ## 15. How do you create a _middleware_ that logs the _request method_ and _URL_ for every request? 783 | 784 | In Express.js, **middlewares** allow you to handle HTTP requests. Here, you will learn how to create a simple **logging middleware** that records the request method and URL. 785 | 786 | ### Setting Up the Express App 787 | 788 | First, install Express via npm, and set up your `app.js` file: 789 | 790 | ```javascript 791 | const express = require('express'); 792 | const app = express(); 793 | ``` 794 | 795 | ### Creating the Logging Middleware 796 | 797 | Define a logging function that extracts the request method and URL, and then use `app.use()` to mount it as middleware. 798 | 799 | ```javascript 800 | // Logging Middleware 801 | const logRequest = (req, res, next) => { 802 | console.log(`Received ${req.method} request for: ${req.url}`); 803 | next(); // Call next to proceed to the next middleware 804 | }; 805 | 806 | // Mount the middleware for all routes 807 | app.use(logRequest); 808 | ``` 809 | 810 | ### Testing the Setup 811 | 812 | Use `app.get()` to handle GET requests, and `app.listen()` to start the server. 813 | 814 | ```javascript 815 | // Sample route 816 | app.get('/', (req, res) => { 817 | res.send('Hello World'); 818 | }); 819 | 820 | // Start the server 821 | app.listen(3000, () => { 822 | console.log('Server is running on port 3000'); 823 | }); 824 | ``` 825 | 826 | When you visit `http://localhost:3000/` in your browser and check the server console, you should see the request being logged. 827 |
828 | 829 | 830 | 831 | #### Explore all 58 answers here 👉 [Devinterview.io - Express.js](https://devinterview.io/questions/web-and-mobile-development/express-interview-questions) 832 | 833 |
834 | 835 | 836 | web-and-mobile-development 837 | 838 |

839 | 840 | --------------------------------------------------------------------------------