2016-06-23 48 views
0

我有4箇中間件函數:a,b,c,dExpressJS基於請求參數的分支路由

如果體內含有一種價值X,我想執行a然後b,否則我想執行c然後d

我的代碼如下所示:

app.post('/', (req, res, next) => { 
    if (req.body.X) { 
    next(); 
    } else { 
    next('route'); 
    return; 
    } 
}, a, b); 

app.post('/', c, d); 

是否有這一個更優雅的方式?有沒有使這些路由器更具可讀性的方法(或軟件包)?

+0

檢查每個中間件中的req.body.x並製作唯一路由:app.post('/',a,b,c,d) –

回答

1

我認爲你不需要有兩條路線。您可以在中間件ab中檢查req.body.X

// Middlewares a and b 
module.exports = function(req, res, next){ 
    if(req.body.X){/* Do stuff */} // if is the middleware "a" call next() 
           // else, is "b" finish with a response i.e. res.send() 
    else next(); 
} 

// Middlewares c and d 
module.exports = function(){ 
    // Do whatever, if middleware "c" call next() else finish with a response 
} 

// Route 
app.post('/', a, b, c, d);