2014-10-17 135 views
1

沒有求助於正則表達式反正是有與expressjs遞歸調用路由即URL例子:遞歸Expressjs路由

/f:forum/s:section/t:thread/p:post 
/f:forum/s:section/s:section/t:thread/p:post 
/f:forum/s:section/s:section/s:section/t:thread/p:post 
... 

因此技術上允許在論壇「分段/小分段」的無限量。

我試圖做的事:

app.js:

var express = require('express'); 
app = express(); 
app.route('/').get(function(req, res, next){ 
    return res.send('hello'); 
}); 
app.use('/f:forum', require('./section')); 
server = app.listen(process.env.http || process.env.PORT); 
module.exports = app; 

section.js:

var router = require('express').Router(); 
router = router; 
router.route('/s:section').get(function(req, res, next){ 
    return res.send(req.params); 
}); 
router.use('/s:section', require('./thread')); 
module.exports = router; 

thread.js:

var router = require('express').Router(); 
router.use('/s:section', require('./section')); 
router.route('/t:thread/p-:post').get(function(req, res, next){ 
    return res.send(req.params); 
}); 
router.route('/t:thread').get(function(req, res, next){ 
    return res.send(req.params); 
}); 
module.exports = router; 

但有趣的是它告訴我在thread.js require('./section') = {}
尚未在app.js中,這是正確的...任何建議?

回答

2

您可以執行通配符路由,如router.route('/:path*'),然後從那一點開始解析處理程序。

例如,像:

router.route('/forum/:path*', function(req,res){ 
    var requestPath = req.path; // will present the whole path to you for parsing 
    // do whatever db lookup logic you normally would do now that you have the pieces you wanted 
    res.render('forum', data); 
}; 
+0

可否請你展示一個小的處理器解析部分。 (足夠讓我得到你的意思) – gabeio 2014-10-20 19:47:51

+1

更新到演示它 – Paul 2014-10-21 16:53:09

+0

謝謝!真的有幫助! – gabeio 2014-10-22 01:28:41