Problem picking query params in URL by Express

Asked

Viewed 2,377 times

0

I’m creating a route GET which returns an item from a user array, but has no return when used req.query.id. When I use req.params.id right, but in that case I want to test for query string even.

const express = require('express');
const app = express();

const users = ['junyor', 'Antonio', 'joao'];

app.get('/users/:id', (req, res) => {
    const id = req.query.id;
    return res.json(users[id]);
});

app.listen(3000);

The URL accessed was localhost:3000/users?id=1.

The response from the server:

Cannot GET /users
  • to use query, not just leave the route as app.get('/users', () => {})?

1 answer

3


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.

  • 1

    Perfect, now it was clear. I imagined that I always needed to declare the variable on the route, but now it worked out! vlw friend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.