如果我有一条有多个参数的路线,我怎样才能将这两个参数链接起来?

时间:2014-06-03 18:55:40

标签: javascript express parameters url-routing

这就是我认为可以做到的事情,我没有得到预期的结果。

router.param('param_1', function(req, res, next, param){
   req.param_1 = param;
   next();
});

router.param('param_2', function(req, res, next, param){
   req.param_1.param_2 = param;
   next();
});

router.get(':param_1/urlstuff/:param_2', function(req, res){
    console.log(req.param_1);
    console.log(req.param_1.param_2);
    res.send('done');
});

1 个答案:

答案 0 :(得分:0)

问题在于我将该值视为对象,但它是一个字符串。

如果我们先声明一个对象并将值赋给它的属性,然后再将其赋值给请求对象,那么在child参数中我们将能够链接第二个值。

router.param('param_1', function(req, res, next, param){
   var param_1 = {};

   param_1.value = param;    

   req.param_1 = param_1;
   next();
});

router.param('param_2', function(req, res, next, param){
   req.param_1.param_2 = param;
   next();
});

router.get(':param_1/urlstuff/:param_2', function(req, res){
   console.log(req.param_1); // logs an object with value property and param_2 string value.
   console.log(req.param_1.param_2); // logs param_2 string value
   res.send('done');
});