Back to Interview PrepGet interview ready with AILearn each topic the way interviewers ask it, then answer like you would in the interview.
Course progress0/12 chapters · 0%

Chapter 2 of 13

~11 min

Routing

Routing is how an Express app decides which function should handle a given combination of HTTP method and URL path. Getting comfortable with app.get/post/put/delete and route paths is the first real building block of any Express application.

HTTP Methods as Route Methods

Express exposes a method on the app object for each common HTTP verb - app.get(), app.post(), app.put(), app.patch(), app.delete() - each taking a path and one or more handler functions. A route only matches when both the method and the path line up, so the same path can have entirely different handlers depending on the verb used to request it.

server.js
const express = require('express');
const app = express();

app.get('/tasks', (req, res) => {
  res.json({ tasks: [] });
});

app.post('/tasks', (req, res) => {
  res.status(201).json({ message: 'Task created' });
});

app.delete('/tasks', (req, res) => {
  res.json({ message: 'All tasks deleted' });
});

app.listen(3000);
The same path, different methods

Static and Dynamic Route Paths

A route path can be a fixed string like /tasks, or it can contain named parameters (prefixed with a colon, like /tasks/:id) that match any value in that position of the URL. Express also supports pattern-matching using string wildcards, though named parameters are by far the most common way to capture identifiers out of a URL.

server.js
app.get('/tasks/:id', (req, res) => {
  res.json({ id: req.params.id });
});

// GET /tasks/42  ->  { id: '42' }

Chaining Routes with app.route()

When several HTTP methods share the same path, repeating that path for each app.get/post/put call is a common source of typos and drift. app.route(path) returns a route object you can chain .get(), .post(), .put(), and .delete() calls onto, so the path is written once and every handler for it stays visually grouped together.

server.js
app.route('/tasks/:id')
  .get((req, res) => {
    res.json({ id: req.params.id, title: 'Sample task' });
  })
  .put((req, res) => {
    res.json({ id: req.params.id, updated: true });
  })
  .delete((req, res) => {
    res.status(204).end();
  });
Grouping methods for one path with app.route()

Route Order Matters

Express checks routes in the order they were registered and uses the first one that matches, so a more general route defined earlier can accidentally "shadow" a more specific one defined after it. A common example is registering /tasks/:id before /tasks/new - since :id matches any string, a request for /tasks/new will hit the :id handler first unless /tasks/new is registered above it.

Coding challenge

Using app.route(), create a single route definition for the path /users/:id that responds to GET with a JSON object echoing the id, and to DELETE with a 204 No Content status.

// Write your solution here

Answer every question below to mark this chapter as complete.

Quiz Yourself

Score: 0/4

1. What determines whether a given Express route handler runs for an incoming request?

2. In a route path like /tasks/:id, what is `:id`?

3. What is the main benefit of using app.route(path) over repeating app.get/post/put with the same path string?

4. Why can registering /tasks/:id before /tasks/new cause a bug?

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in