简体   繁体   English

快速路线参数

[英]Express route parameters

I'm new to Node.js and Express and I'm wondering the if the following code is correct: 我是Node.js和Express的新手,我想知道以下代码是否正确:

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? 那么,Express如何找出只使用一个参数就使用哪一条路线呢? 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"? 例如,当我调用localhost:3000/students/20 ,如果有些学生20岁,而有些学生的名字是“ 20”,该怎么办?

You should use req.query in such conditions. 您应该在这种情况下使用req.query。 Like: /students?name=john&age=25 像: /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 : 您可以使用regex进行路由匹配

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. 据我所知,Express使用的是第一种与您的URL模式匹配的方法,而无需区分路由参数的类型。

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. 为了能够同时使用名称和年龄过滤器,您将必须使用查询参数或将字符串化的JSON传递给包含两个过滤器的路由。 The former would be a little more graceful, though, reducing the URL's overload. 不过,前者会更优雅一些,从而减少URL的过载。 JSONs tend to get big. JSON往往会变大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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