0

I'm new to Node.js and Express and I'm wondering the if the following code is correct:

router.get('students/:name', async (req, res) => {
    const students = await Student.find(req.params.name);
    res.send(students);
});

router.get('students/:age', async (req, res) => {
    const students = await Student.find(req.params.age);
    res.send(students);
});

So how can Express figure out which route to use one passing only one parameter? For example, when I call localhost:3000/students/20, what if some students are 20 years old and some students have the name of "20"?

Alex Wang
  • 411
  • 3
  • 16
  • no its not correct, `:age` one wont work, also "params" in a GET request should be set in query .ie `students?name=..` or `students?age=..` if it were `students/:id` it would be fine as does not break rest – Lawrence Cherone Aug 21 '19 at 16:32

3 Answers3

2

You should use req.query in such conditions. Like: /students?name=john&age=25

router.get('/students', async (req, res) => {
    let query = req.query; // {name: 'john',age:25}
    const students = await Student.find(query);
    res.send(students);
});
Maxim Pyshko
  • 551
  • 4
  • 14
1

You can use regex for route matching:

router.get('students/:age([0-9]+)', async (req, res) => {
    const studentAge = parseInt(req.params.age, 10);
    const students = await Student.find({age: studentAge});
    res.send(students);
});

// Handle other strings
router.get('students/:name', async (req, res) => {
    const students = await Student.find({name: req.params.name});
    res.send(students);
});
Maxim Pyshko
  • 551
  • 4
  • 14
0

As far as I know myself, Express uses the first method that matches your URL's pattern without differentiating between the route parameters' types.

This means that, in your code, you will always be using the first, topmost method.

In order to be able to use both the name and the age filters, you would have to either use query parameters or pass a stringified JSON to your route containing either of the filters. The former would be a little more graceful, though, reducing the URL's overload. JSONs tend to get big.

Andrei
  • 400
  • 2
  • 6