Express.js & API Development
Express request processing, routing, request bodies, and cross-origin API access.
Q35: What is middleware in Express.js?
Middleware functions have access to the request object (req), response object (res), and the next function to perform code execution, request mutation, or end request cycles.
- Middleware processes incoming requests sequentially.
- Calling
next()passes execution to subsequent middleware functions.
What happens if middleware does not call next() and does not end res?
Q36: What is Express Router and why is it used?
Express Router creates modular, mountable route handlers. Routers allow splitting route definitions into separate files for better code organization and maintainability.
- Enables modular structure for API route handlers.
- Acts as mini-middleware isolated to specific path prefixes.
How do you instantiate an Express router instance?
Q37: Why was body-parser required in Express and how is it used now?
Earlier Express versions required the body-parser module to parse incoming request bodies. Modern Express (v4.16+) includes built-in body parsing via express.json() and express.urlencoded().
- Parses request payload bodies into
req.body. - Built directly into modern Express releases (
express.json()).
How do you parse JSON request bodies natively in modern Express.js?
Q38: What is CORS and how do you enable it in Express.js?
CORS (Cross-Origin Resource Sharing) is a browser security feature that restricts cross-origin HTTP requests. In Express, the cors middleware sets appropriate Access-Control-Allow-Origin HTTP headers.
- CORS prevents browser client access across different domain origins.
- The
corspackage sets standard access headers automatically.
Which HTTP response header allows cross-origin requests?