tezvyn:

Query params vs route params in Express

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

distinguishing two ways to pass data in a URL.

OUTLINE

query string values via req.query.q, named path segments via req.params.id, query is optional, route params are part of the matched pattern.

RED FLAG

mixing up req.query and req.params.

WHAT THIS TESTS This verifies you understand the two distinct mechanisms for passing data through a URL and how Express surfaces each, a daily-use fundamental.

A GOOD ANSWER COVERS Query parameters are the key-value pairs after the question mark in a URL. Express parses them into the req.query object, so for /search?q=nodejs you read req.query.q to get 'nodejs'. They are optional, can appear in any order, and you can have many. Route parameters are named segments declared in the route path with a leading colon, such as app.get('/users/:id'). When a request matches, Express populates req.params with those names, so /users/42 gives req.params.id equal to '42'. Route params are part of the path pattern itself and are required for the route to match. The key distinction: query strings carry optional, often filter-like data, while route params identify a specific resource within the path structure.

COMMON WRONG ANSWERS Reading id from req.query for a /:id route, or reading q from req.params. Assuming route params are optional. Forgetting both values arrive as strings and need parsing if you want numbers.

LIKELY FOLLOW-UPS How do you handle multiple route params like /users/:userId/posts/:postId. How do you parse and validate that an id is numeric. What does req.body hold versus req.query.

ONE CONCRETE EXAMPLE For app.get('/users/:id', (req, res) => res.send(req.params.id + ' ' + req.query.sort)), a request to /users/42?sort=desc gives req.params.id equal to '42' and req.query.sort equal to 'desc'. Swapping the two objects would yield undefined, a frequent beginner bug.

Read the original → expressjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.