Route and Query Parameters

A route parameter such as /games/:id lets one route answer every game, read from req.params, and query parameters such as ?players=4 arrive in req.query, both always as text that you turn into numbers before you compare them.

Apprentice · Node.js · REST API · Updated

By

After this lesson you can

  • Read a route parameter such as /games/:id from req.params, and answer 404 when no item has that id
  • Read query parameters from req.query, and turn their text into numbers before comparing

Key takeaways

  • A path pattern such as /games/:id (read "games colon id") matches /games/3, /games/9 and every other id, and Express puts the part it matched in req.params.id.
  • Query parameters, the name=value pairs after the question mark, arrive in req.query, such as req.query.players. A query parameter that wasn't sent is undefined.
  • Route and query parameters are always text. Turn them into numbers with Number() before you compare them with a number, or "3" === 3 is false and nothing matches.
  • When no item has the id that was asked for, answer 404 with a message that names the id.
  • Express 5 writes path patterns differently from Express 4. An optional part is /games{/:id} and a match-anything path is /*splat; the old :id? and * stop the app at startup.

Almost every API asks "which one?" and "which ones?". A shop shows product 7, a music app shows the songs under four minutes, a job board shows the jobs near you. Each needs a route that reads a value out of the address, and you'll write one in nearly every API you build.

The Rolling Dice café's shelf has grown to four games: the three from Your First Express App: Routes and JSON and Dragon's Picnic. Customers want to look up one game, and to ask which games fit their group.

One route for every game

The café could add app.get("/games/1", ...), app.get("/games/2", ...), and one more route every time a game arrives. Instead, a path pattern can hold a route parameter: a placeholder, written with a colon, that matches whatever is in that part of the path.

app.get("/games/:id", (req, res) => {
  console.log(req.params.id, typeof req.params.id);
  const game = games.find((g) => g.id === Number(req.params.id));
  if (game === undefined) {
    res.status(404).json({ message: `There's no game ${req.params.id}.` });
    return;
  }
  res.json(game);
});

/games/:id is read "games colon id". It matches /games/3 and /games/chess alike, and Express puts the matched part in req.params, under the name after the colon. Send GET /games/3, GET /games/9 and GET /games/chess, and the terminal shows:

3 string
9 string
chess string

Text, not numbers

Every part of an address is text, so req.params.id is the text "3", never the number 3. Comparing text with a number goes wrong without an error:

const id = "3";

console.log(id === 3);
console.log(Number(id) === 3);
console.log(id + 1);
console.log(Number("chess"));
console.log(Number(undefined));
console.log(2 <= Number(undefined));
false
true
31
NaN
NaN
false

=== (read "strictly equal") says text and a number are never equal, and + joins text instead of adding. Write g.id === req.params.id in the route above and GET /games/3 answers {"message":"There's no game 3."}, though game 3 is on the shelf. Number() turns the text into a number first. Text that isn't a number, such as "chess", becomes NaN (not a number), which equals no id.

A 404 for a game that isn't there

find gives back undefined when no game has the id, and that's the moment for a 404 (there's nothing at that address). The answer names what was asked for, so the person reading it knows what went wrong. Each request, then its answer's status line and body:

GET /games/3
HTTP/1.1 200 OK
{"id":3,"title":"Tile Town","minPlayers":1,"maxPlayers":2,"minutes":30,"available":true}

GET /games/9
HTTP/1.1 404 Not Found
{"message":"There's no game 9."}

GET /games/chess
HTTP/1.1 404 Not Found
{"message":"There's no game chess."}

The return after the 404 stops the handler, so it doesn't go on to answer a second time.

Query parameters: the details after the question mark

A group of four asks GET /games?players=4. The part after ? is the query string, and Express reads its name=value pairs into req.query. Change the /games route so it filters when players is there:

app.get("/games", (req, res) => {
  console.log(req.query.players, typeof req.query.players);
  if (req.query.players === undefined) {
    res.json(games);
    return;
  }
  const players = Number(req.query.players);
  const fits = games.filter((g) => g.minPlayers <= players && players <= g.maxPlayers);
  res.json(fits);
});

GET /games?players=4 answers Harbor Lights, Moon Mice and Dragon's Picnic, each made for groups that include four. Tile Town, for one or two players, is left out. GET /games answers all four games, and the terminal shows why the if matters:

4 string
undefined undefined

A query parameter that wasn't sent is undefined, and the last two lines of the earlier output show what Number(undefined) would do: NaN, which fits no game, so GET /games would answer an empty list. A query parameter the route doesn't read, such as ?maxMinutes=30 here, changes nothing.

Express 5 and older examples

Many Express examples online were written for Express 4, whose path patterns had two forms Express 5 doesn't accept: /games/:id? for an optional part, and * to match any path. In Express 5, either one stops the app as it starts:

PathError [TypeError]: Unexpected ? at index 10: /games/:id?; visit https://git.new/pathToRegexpError for info

Express 5 writes an optional part in braces, /games{/:id}, which matches /games and /games/3, and a match-anything path with a name, /*splat. When an older example's pattern stops your app, those are the two to rewrite.

Check yourself

2 questions to try on the lesson page.

So what

One pattern with :id answers every game, and req.query carries the filters, so each "which one?" or "which ones?" is a single route, as long as you remember that everything in an address arrives as text.

Key terms

Related