简体   繁体   English

如何在Express中路由具有“深度”变量的URL?

[英]How can I route URLs with variable “depth” in Express?

I'm currently learning the MEAN-Stack and writing a tool in my API which multiplies a series of numbers. 我目前正在学习MEAN-Stack,并在我的API中编写了一个将一系列数字相乘的工具。 I have two questions for which the Express Documentation did not provide answers. 我有两个问题,快速文档未提供答案。

  1. How can I route for URLs of variable depth? 如何路由可变深度的URL? Currently, I'm doing the following: 目前,我正在执行以下操作:

 router.route('/multiply/:a/:b') .get(function(req,res){ /*multiply*/ return res.send(respone); }); 

As you can see I can only multiply 2 numbers this way, not as many as I like, and this approach routes anything, not just numbers for a & b. 如您所见,我只能以这种方式将2个数字相乘,而不是我想要的数量,并且这种方法可以路由任何内容,而不仅仅是a和b的数字。 So my second question is how do I route only for numbers as a & b? 因此,我的第二个问题是如何仅将数字作为a和b进行路由?

Regards, Claas M. 此致Claas M.

You can use a wildcard route to match all numbers and then just do an explosion of the request params yourself: 您可以使用通配符路由来匹配所有数字,然后自行扩展请求参数:

// matches /multiply/1/3/4/5/32/4 etc...
router.route('/multiply/:numbers([0-9]+)*')
  .get(function(req, res){

    // req.params.numbers will equal /1/3/4/5/32/4
    var numbers = req.params.numbers.split('/');
    // ..
    // multiply numbers
    // ..
    return res.send(answer);

  }); 

Express Route tester is a really useful tool: http://forbeslindesay.github.io/express-route-tester/ Express Route测试仪是一个非常有用的工具: http : //forbeslindesay.github.io/express-route-tester/

After I put far too much effort into this I concluded that it is easier to just use POST instead of putting the data into the URL. 在我花了太多精力之后,我得出结论,使用POST而不是将数据放入URL更容易。 But if someone knows a solution I will still be grateful. 但是,如果有人知道解决方案,我将不胜感激。

 router.route('/multiply/:a/:b') .post(function(req,res){ var array = req.body.numbers; /*multiply*/ return res.send(respone); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM