如何在Express应用中设置多选路线?

时间:2019-04-16 03:59:17

标签: node.js express routes

我已经在我的Express应用中定义了一条路线:

app.get('/ts/:space/:mode/:param1/:param2/:fromdate/:todate',(req,res,next) =>{...})

但是现在,如果:space参数等于特定值,我想添加额外的参数。例如,如果:spaceblah,则路由应转换为

app.get('/ts/:space/:mode/:param1/:param2/:param3/:fromdate/:todate',(req,res,next) =>{...})

是否可以不对blah关键字进行硬编码并将硬编码的路径放在通用路径之前?

2 个答案:

答案 0 :(得分:0)

添加额外的参数会将其呈现为一条新的独特路由,因此,我认为只要遇到:space = blah,都应该执行到该新路由的重定向。

res.redirect()

根据OP请求添加了代码

app.get('/ts/:space/:mode/:param1/:param2/:fromdate/:todate', (req, res, next) => {
  let param3 = 'sample';
  if (req.params.space === 'blaah') {
    res.redirect(`/ts/${req.params.space}/${req.params.mode}/${req.params.param1}/${req.params.param2}/${param3}/${req.params.fromdate}/${req.params.todate}`);
  }
});

答案 1 :(得分:0)

拆分处理程序函数以隔离函数。

app.get('/ts/:space/:mode/:param1/:param2/:fromdate/:todate', handler1)

app.get('/ts/:space/:mode/:param1/:param2/:param3/:fromdate/:todate', handler2)

并欺骗handler1特殊情况:

const handler1 = (req,res,next) => {
  if (req.params.space === "blah") {
    // use hanler for `/ts/:space/:mode/:param1/:param2/:param3/:fromdate/:todate` route
    // force set param3 value,
    req.params['param3'] = "maybe_a_default_value";
    return handler2(req,res,next);
  }
  // handler for `/ts/:space/:mode/:param1/:param2/:fromdate/:todate` route
}

const handler2 = (req,res,next) => {
  // handler for `/ts/:space/:mode/:param1/:param2/:param3/:fromdate/:todate`
  // now, req.params.space === "blah" and req.params.param3 === "maybe_a_default_value" 
}