2016-08-02 72 views
0

在我website.com/v2/bridge/:locationId/process端點,傳入req.body看起來是這樣的:快車 - 有條件路由

{ 
    choice: 'a', 
    data: [ 
    { 
     ... 
    }, 
    ... 
    ] 
} 

我想這取決於什麼req.body.choice值訪問特定的路線。如果req.body.choice === 'a'那麼我想繼續website.com/v2/bridge/:locationId/process/choiceA,而傳遞相同的req

我不知道我需要用什麼中間件來完成這個任務。我不知道這是否可能。

我極度簡化路線:

// website.com/v2/bridge 
const proc = require('./process'); 

router.use('/:locationId/process', proc); 

module.exports = router; 




// website.com/v2/bridge/56/process 
router.use(function (req, res, next) { 
    // ????????????????????????? 

    next(); 
}); 

const choiceA = require('./choice-a'); 
const choiceB = require('./choice-b'); 

router.use('/choice-a', choiceA); 
router.use('/choice-b', choiceB); 

module.exports = router; 





// website.com/v2/bridge/56/process/choice-a 
router.post('/', function (req, res) { 
    res.send('I got here.'); 

    return; 
}); 

module.exports = router; 

什麼中間件的功能,我需要包括有條件地路由我的要求?我試圖避免一個巨大的函數if語句根據req.body.choice的值處理不同的事情。

回答

3

這將是你麻煩一點...試試看

router.use(function (req, res, next) { 
    req.path = "/" + "choice-"+req.body.choice 
    req.url = "/" + "choice-"+req.body.choice 
    next(); 
}); 

現在it'will的要求去做到終點,你想

+0

我無法改變'req.path ',但我可以重新分配'req.url',這對我來說非常合適。 – Jacob

+0

偉大的工作,這幫助了我很多。 –