2016-04-11 69 views
0

我嘗試使用express.Router()獲取可選的URL參數,但它不工作。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 {} 
}); 

如何正確解決這個問題?謝謝。

回答

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; 
+0

謝謝。這工作:) – dragfire