代码之家  ›  专栏  ›  技术社区  ›  Vandervals

快速路由器在子目录下无法正常工作

  •  0
  • Vandervals  · 技术社区  · 6 年前

    我正在用Node.js应用程序中的模块划分我的api查询。因此在 index.js 我有:

    app.use('/api/schedule/', apiSchedule);
    

    然后,在apiSchedule路由器中:

    router.get('/:id', function (req, res) {
        res.send('Queried ID');
    });
    router.get('/', function (req, res) {
        res.send('Queried root');
    });
    router.get('/list', function (req, res) {
        res.send('Queried list');
    });
    router.get('/list/:id', function (req, res) {
        res.send('Queried list item');
    });
    

    我正在和邮递员测试这些路线,结果是:

    http://localhost/api/schedule/ <-- Queried root
    http://localhost/api/schedule/1 <-- Queried ID
    http://localhost/api/schedule/list  <-- empty
    http://localhost/api/schedule/list/ <-- empty
    http://localhost/api/schedule/list/1 <-- Queried list item
    

    为什么查询列表会给出空响应?我的配置有问题,或者路由器没有按我预期的那样工作?

    注意,有 没有错误响应,只有空白响应 . 也, console.log 路由器内部的功能不会被调用。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Logans    6 年前

    可能是因为路径 /:id 具有参数ID,因此此路由的regex也可以接受路由 / /list 可以。

    检查的值 req.params 在里面 /:id号 路线你会看到的以防万一 / ID参数将是 undefined /列表 如果是的话 list .

    要修复它,需要为 /:id号 ,如果ID是类型号,则它将如下所示 /:id(\d+) .

    我对UUID4(字符串)类型的ID参数也有同样的问题,所以我设法使用这个regex修复它 ([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})