It is necessary to understand the difference between a route parameter and a query string of route.
Note in your code:
app.get('/users/:id', (req, res) => {
// ...
});
The path you set in the first argument of get
explicitly a route param, that is, a parameter that must be part of the request path. Thus, if you make a request to /users?id=1
, that Handler route - requiring a parameter - will not be executed.
A route parameter is different from a "parameter" query string, see:
Examples
/users/1
: 1
would be the route parameter :id
.
/users/foo-bar
: foo-bar
would be the parameter :id
.
Note that :id
does not require any specific format. As long as it is valid in a URL, it will be properly captured.
One query string, on the other hand, may be attached on any route.
/users/1?paramName=paramValue
: 1
would be the route parameter :id
and paramValue
would be the value of the query string paramName
.
Thus, to access a parameter of query string, utilize req.query
. In parallel, to access a route parameter, use req.params
.
Then your code will look like this:
app.get('/users/:id', (req, res) => {
const id = req.params.id;
return res.json(users[id]);
});
In short, it makes no sense to declare route param in the route URL if you do not intend to use it, then if you find the format of query string param more valid in your case, can do:
app.get('/users', (req, res) => {
const id = req.query.id;
return res.json(users[id]);
});
Note that in the latter case, as the parameter :id
(or any other) is not required in the URL, the route Handler will be executed normally.
To learn more, see documentation on Express routing.
to use
query
, not just leave the route asapp.get('/users', () => {})
?– Cmte Cardeal