express.Router()获取带有可选参数的url路由

时间:2016-04-11 19:40:07

标签: node.js express

我尝试使用express.Router()获取可选的URL参数,但它无效。

如果我使用app.get,它工作正常:

app.get('/videos/:category', function(req, res){
    // localhost:9876/videos/music
    debug(req.params); // This is working as expected
});

唯一的问题是当我尝试使用express.Router()时这样使用。 我试过这样的事:

app.js:

var express = require('express');
var app = express();

var videos = require('./routes/videos');

app.use('/videos/:category', videos);

路由/ videos.js:

var express = require('express');
var router = express.Router();

router.get('/:category', function(req, res){
    debug(req.params, req.params.category); // req.params is empty {}
});
module.exports = router;

我也尝试过这样:

router.get('/', function(req, res){
        debug(req.params, req.params.category); // req.params is empty {}
});

如何正确解决这个问题?感谢。

1 个答案:

答案 0 :(得分:2)

在你的两种解决方案中,你都走错了路。在第一种情况下,它是/videos/:category/:category,在第二种情况下是/videos/:category/。您需要将参数移至router.js router.get并将其从app.js app.use中删除:

<强> app.js:

var express = require('express');
var app = express();

var videos = require('./routes/videos');

app.use('/videos', videos);

<强>路由/ videos.js:

var express = require('express');
var router = express.Router();

router.get('/:category', function(req, res){
    debug(req.params, req.params.category); // req.params is empty {}
});
module.exports = router;