NodeJs express.Router解析为错误的路径

时间:2018-04-09 08:41:01

标签: node.js express

我的路由器设置如下:

'use strict';

const express = require('express');
const controller = require('../../module/controllers/controller');

const router = express.Router();

router.get('/:param', controller.getEntity);
router.get('/', controller.getEntities);
router.put('/:param', controller.updateEntity);
router.post('/update/:param', controller.updateEntity);
router.get('/subpath', controller.getEntityPath);

module.exports = router;

以上所有路线都有父路线:parent

当我尝试拨打http://hostname/parent/subpath时,它会继续http://hostname/parent/。只有当我注释掉以下行时,subpath才可用:

'use strict';

const express = require('express');
const controller = require('../../module/controllers/controller');

const router = express.Router();

// router.get('/:param', controller.getEntity);
// router.get('/', controller.getEntities);
router.put('/:param', controller.updateEntity);
router.post('/update/:param', controller.updateEntity);
router.get('/subpath', controller.getEntityPath);

module.exports = router;

我在配置中做错了什么?

2 个答案:

答案 0 :(得分:1)

您需要撤消路线的顺序:

'use strict';

const express = require('express');
const controller = require('../../module/controllers/controller');

const router = express.Router();

router.get('/', controller.getEntities);
router.post('/update/:param', controller.updateEntity);
router.get('/subpath', controller.getEntityPath);
router.get('/:param', controller.getEntity);
router.put('/:param', controller.updateEntity);
module.exports = router;

因为http://hostname/parent/subpath首先匹配/:param

答案 1 :(得分:0)

尝试将绝对路线放在相对路线之上。

router.post('/update/:param', controller.updateEntity);
router.get('/subpath', controller.getEntityPath);    
router.put('/:param', controller.updateEntity);