简体   繁体   中英

Express route parameters

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"?

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);
});

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);
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM