Chuyển đến nội dung

Bài 8 · Routing

Route Parameters and Query Strings

Read data from the URL in Express: req.params, req.query, parsing numbers safely, and the Express 5 path syntax changes for wildcards and optional parameters.

URLs carry data in two places. Route parameters are parts of the path, as in /users/42, where 42 identifies one user. A query string is the optional part after the ?, as in /users?role=admin&page=2, which usually filters or shapes a list. Express gives you both as plain objects: req.params and req.query.

Everything read from a URL is text. A good habit is to treat it as untrusted input: convert it, check it, and handle bad values. This lesson also covers how Express 5 changed path syntax, which breaks some older tutorials.

Route parameters

Put a colon before a name in the path and Express captures that segment:

JavaScript
app.get('/users/:id', (req, res) => {
  res.json({ id: req.params.id });
});

app.get('/posts/:year/:month', (req, res) => {
  const { year, month } = req.params;
  res.json({ year, month });
});

A request to /users/42 gives req.params = { id: '42' }. Notice the value is the string '42', not a number. A parameter matches one path segment, up to the next /. Characters such as %20 are decoded for you.

Two ways to read the URL

Params Part of the path. Identify one thing.
Query After the question mark. Filter or tune.

Both arrive as strings.

1 / 2

Query strings

For /search?term=node&limit=5, Express fills req.query for you, with no route syntax at all:

JavaScript
app.get('/search', (req, res) => {
  const { term, limit } = req.query;
  res.json({ term, limit });
});

Query keys are not part of the route, so /search, /search?x=1 and /search?term=a all hit the same handler. Express 5 uses a simple parser by default, so a repeated key such as ?tag=a&tag=b becomes an array, while nested syntax like ?filter[role]=admin is not expanded into an object as it was in Express 4 (which used the qs library). You can switch back with app.set('query parser', 'extended') if you need it.

Any key can be missing, so give defaults:

JavaScript
const page = Number(req.query.page ?? 1);

Parsing numbers safely

Number('abc') is NaN, and Number('') is 0, so convert and then validate:

Node.js Params and query with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The three outcomes are worth memorizing: a malformed value is a 400 Bad Request, a well-formed value that points at nothing is a 404 Not Found, and success is a 200. Dedicated validation libraries come later in Validating Input.

Express 5 path syntax

Express 5 upgraded its path matcher (the library path-to-regexp, version 8). The new rules are stricter and easier to reason about. Old patterns using regular-expression characters do not work any more.

Goal Express 4 Express 5
Match anything after /files/ /files/* /files/*path
Optional parameter /users/:id? /users{/:id}
Optional segment group /docs/(v2/)?intro /docs{/v2}/intro
Match any path * /*splat
Regex inside a path /:id(\\d+) Not supported: validate in code
JavaScript
// Named wildcard: the value is an array of path segments in Express 5
app.get('/files/*path', (req, res) => {
  res.json({ segments: req.params.path });
});
// GET /files/docs/2024/report.pdf  ->  ['docs', '2024', 'report.pdf']

// Optional parameter with braces
app.get('/users{/:id}', (req, res) => {
  res.json({ id: req.params.id ?? null });
});
// GET /users -> null, GET /users/5 -> '5'

Two details trip people up. A bare * is now an error, so wildcards need a name. And the wildcard value is an array of segments, not one string. If an old route throws a path syntax error when you upgrade, this table is the first place to look.

The runnable demo below implements the same rules on a stand-in matcher so you can see the captured values. This is our simplified copy of the syntax, not the real library, so it only knows :name, *name and groups.

Node.js A tiny Express 5 style path matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

/users/:id does not match plain /users (the result is null), while /users{/:id} does and leaves id out. The wildcard turns docs/2024/report.pdf into an array. Pattern /files/*path does not match /files alone, since a wildcard needs at least one segment.

Several parameters and reusable logic

A route can have several parameters, and you can validate one centrally with app.param-style middleware (covered with routers in express.Router). For one-offs, a small helper keeps handlers tidy:

JavaScript
function parseId(value) {
  const id = Number(value);
  return Number.isInteger(id) && id > 0 ? id : null;
}

app.get('/orders/:id', (req, res) => {
  const id = parseId(req.params.id);
  if (id === null) return res.status(400).json({ error: 'Invalid id' });
  res.json({ order: id });
});

Security note

Never build SQL, file paths or shell commands from req.params or req.query by joining strings. A parameter such as ../../etc/passwd or 1; DROP TABLE users is just text until you misuse it. Use parameterized queries and validate. The security lesson covers this properly.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. For GET /users/42, what is the type and value of req.params.id?

    URL data is always text, so you must convert it yourself, for example with Number().
  2. 2. Which Express 5 route makes the id optional?

    Express 5 uses braces for optional parts. The old trailing question mark is not valid.
  3. 3. A request to /users/abc where id must be an integer. What status fits best?

    The value is malformed, so the client made a bad request. A 404 fits a valid id that does not exist.
  4. 4. What does req.query contain for /search?tag=a&tag=b in Express 5's default parser?

    Repeated keys become an array. Nested bracket syntax is not expanded by the simple parser.

Summary

  • req.params holds values from :name segments; req.query holds values after the ?. Both are strings.
  • Convert and validate: bad format is 400, valid but missing is 404.
  • Express 5 wildcards must be named (/files/*path, giving an array) and optional parts use braces.
  • Regex fragments inside paths are no longer supported; check values in code.
  • Never put URL values straight into SQL, file paths or commands.

Next: Modular Routing with express.Router.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.