简体   繁体   中英

NodeJs express.Router resolves to wrong path

I have a router setup like below:

'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;

All the above routes have a parent route: parent

When I try to call http://hostname/parent/subpath it keeps going to http://hostname/parent/ . Only when I comment out the below lines, subpath becomes available:

'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;

What am I doing wrong in the configuration?

You need to reverse the order of the routes :

'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;

Because http://hostname/parent/subpath matches /:param first.

Try to put absolute routes above the relative routes.

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

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