Skip to content

Chapter 5 of 8

Building Web Applications with Express

Express.js is the most widely used web framework on top of Node.js, and its core concept is middleware. A middleware function receives the request object (req), the response object (res), and a next function. It can run arbitrary code, modify req or res, end the request-response cycle, or call next() to pass control to the next middleware in the chain. Middleware executes in the order it is defined with app.use() or route methods, flowing top-down. If a middleware never calls next() and does not send a response, the request hangs indefinitely. Error-handling middleware is distinguished by having four parameters, (err, req, res, next), and should always be defined last so it can catch errors propagated from earlier middleware.

Express supports several kinds of middleware. Application-level middleware is bound to the app with app.use(). Router-level middleware is bound to an express.Router() instance, useful for modular route organization. Built-in middleware such as express.json() and express.urlencoded() parse incoming request bodies, while express.static() serves files. Third-party middleware like cors, helmet, and morgan add features like cross-origin support, security headers, and request logging.

Creating a REST API in Express is straightforward: create an app, attach middleware such as express.json() to parse JSON bodies, then define routes for each endpoint using HTTP verbs. Route parameters, defined with a colon prefix like /users/:id, are accessed via req.params and identify a specific resource. Query strings, the part of a URL after a question mark such as /users?role=admin, are accessed via req.query and are typically used for filtering, sorting, or pagination. RESTful design recommends using nouns for endpoints (/api/users rather than /api/getUsers), using proper HTTP methods (GET, POST, PUT, DELETE), returning appropriate HTTP status codes (200, 201, 204, 400, 401, 403, 404, 500), keeping requests stateless, and supporting filtering and pagination. Cross-origin requests from browsers can be enabled with the cors middleware, and incoming data should be validated with libraries like express-validator or Joi to ensure that requests meet expected formats before processing.

All chapters
  1. 1Foundations of Node.js and the Event Loop
  2. 2Module Systems
  3. 3Streams and Buffers
  4. 4Asynchronous Programming
  5. 5Building Web Applications with Express
  6. 6Core Built-in Modules
  7. 7Package Management and Project Configuration
  8. 8Error Handling, Process Management, and Events

Drill it

Reading is not remembering. These come from the Nodejs Runtime deck:

Q

What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 engine. It allows running JavaScript outside the browser, using an event-driven, non-blocking I/O model tha...

Q

What is the Node.js event loop?

The event loop is the mechanism that allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded. It continuously checks the...

Q

What are the phases of the Node.js event loop?

Timers – executes setTimeout and setInterval callbacksPending callbacks – I/O callbacks deferred to next iterationPoll – retrieves new I/O eventsCheck – execute...

Q

What is the difference between setImmediate() and setTimeout()?

setImmediate() executes in the check phase of the event loop, after the poll phase completes. setTimeout(fn, 0) executes in the timers phase on the next iterati...