[英]How to capture indefinite number of parameters in Express Route?
Say I have an express route that takes numbers, adds them all up and returns the total. 假设我有一条快速路线,可以接受数字,将所有数字相加并返回总数。
Normally I would do something like this 通常我会做这样的事情
app.get('/add/:num1/:num2/:num3', (req, res) => {
// access and parseInt these values from req.params
// do operations
// return total
})
In this case, however, the number of parameters the route can handle is limited to 3 (or however many url parameters I hard code). 但是,在这种情况下,路由可以处理的参数数量限制为3(或者,许多URL参数是硬编码的)。 What if I wanted to handle an indefinite or unknown number of parameters? 如果我想处理不确定数量或未知数量的参数怎么办? In this case, numbers? 在这种情况下,数字?
Ultimately I want the route to be able to handle 2, 3, 5, 10, or 20 numbers if that's what the user sends. 最终,我希望路由能够处理用户发送的2、3、5、10或20个数字。
How can I achieve that? 我该如何实现?
Express route supports * wildcard . 快速路由支持*通配符。 You can get all the numbers using '*' 您可以使用“ *”获取所有数字
app.get('/add/*', (req, res) => {
const paramsArray = req.params[0].split('/');
// req.params[0] contains all the params separated by '/'
// split the params using split function and it will return an array containing all parameters
})
This array can be used to iterate over params. 该数组可用于迭代参数。
eg req.params[0] for GET /add/1/2/4/6
will return 1/2/4/6
and after splitting using split function it will be [1,2,4,6]
. 例如GET /add/1/2/4/6
1/2/4/6的req.params [0]将返回1/2/4/6
并且在使用split函数进行拆分之后,它将为[1,2,4,6]
。 And finally add operation can be done on elements of array. 最后,添加操作可以在数组元素上完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.