Node.js ยท Chapter 18 of 43

Express Routing

Express routing maps HTTP methods and URL patterns to handler functions using methods like `app.get()`, `app.post()`, `app.put()`, and `app.delete()`.

Express also supports route parameters (like `/users/:id`) to capture dynamic parts of a URL.

Route methods

Each HTTP verb has a corresponding Express method, letting you define exactly how each endpoint should respond.

Route parameters

Segments prefixed with `:` in a route path become available on `req.params`, letting you build dynamic routes.

Example 1 (javascript)
app.get('/users/:id', (req, res) => {
  res.send('User ID: ' + req.params.id);
});
Output
User ID: 42

Visiting /users/42 captures '42' as req.params.id.

Example 2 (javascript)
app.route('/books')
  .get((req, res) => res.send('List books'))
  .post((req, res) => res.send('Create book'));
Output
List books / Create book

app.route() chains multiple HTTP methods for the same path.

Key points

  • app.get/post/put/delete map HTTP verbs to routes.
  • Route params like :id are captured in req.params.
  • app.route() chains methods for a single path.
  • Routing is central to building REST APIs in Express.
๐Ÿ’ก Note: You can also use `express.Router()` to organize routes into separate files.

๐Ÿ“ Quick Quiz

1. Where do route parameters like :id end up?

2. Which method handles POST requests in Express?

3. What does express.Router() help with?