获取带有可选参数的URL路由

获取带有可选参数的URL路由

本文介绍了express.Router()获取带有可选参数的URL路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用express.Router()获得可选的URL参数,但是它不起作用.

I tried to get optional URL parameter using express.Router(), but it's not working.

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

If I use app.get, it is working correctly:

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

唯一的问题是当我尝试通过express.Router()使用这种方法时.我已经这样尝试过:

The only problem is when I try to use like this using express.Router().I've tried like this:

app.js:

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

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

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

routes/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 {}
});

如何正确解决此问题?谢谢.

How to solve this properly? Thanks.

推荐答案

在两种解决方案中,您得到的路线都是错误的.第一种情况是/videos/:category/:category ,第二种情况是/videos/:category/.您需要将参数移至router.js router.get 并将其从app.js app.use :

In your both solutions you are getting the wrong route. In the first case it's /videos/:category/:category, in the second case - /videos/:category/. You need to move parameter to router.js router.get and remove it from app.js app.use:

app.js:

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

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

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

routes/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;

这篇关于express.Router()获取带有可选参数的URL路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:44