Express JS路由可选参数

时间:2019-02-20 05:47:14

标签: node.js express

我有这样的路由器

app.get('/users/:id',  (req, resp) => {
var id = req.params.id;
if (id) {
    Users.findById(id, (error, record) => {
        if (error) resp.send(error);
        resp.send(record);
        resp.end();
    });
} else {
    // return all users
    Users.find({}, (error, recordset) => {
        if (error) resp.send(error);
        resp.send(recordset);
        resp.end();
    });
}    
});

路径/users/164564正常工作,但路径/users未到达路由并返回错误消息,如打击

  

无法获取/用户

我可以为路径app.get('/users',()=>{});创建两条路由,例如/users和为路径app.get('/users/:id',()=>{});创建/users/164564

是否可以将id保留为可选参数?如果id参数没有值,则返回所有记录。

1 个答案:

答案 0 :(得分:0)

尝试一下

app.get('/users/:id?',  (req, resp) => {...  // question mark was missing.

代替

app.get('/users/:id',  (req, resp) => {...

这可能会帮助您。.谢谢

相关问题