最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Variable number of route params in express? - Stack Overflow

programmeradmin2浏览0评论

cex.io's RESTful API has an interesting route with a variable amount of parameters returning pairs of all currencies given.

How is this achieved in express?

Here's a pseudocode-type example of what I mean...

app.get('/pairs/:arg1/:arg2/:argn...', function(req, res, next) {
    // app logic
});

cex.io's RESTful API has an interesting route with a variable amount of parameters returning pairs of all currencies given.

How is this achieved in express?

Here's a pseudocode-type example of what I mean...

app.get('/pairs/:arg1/:arg2/:argn...', function(req, res, next) {
    // app logic
});
Share Improve this question asked Aug 4, 2017 at 7:15 Mathieu BertinMathieu Bertin 4657 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

In express you can use wildcards like * in your routes, it also supports Regex which you could use, here is an example of how you could achieve this

app.get('/pairs/*', function(req, res) {
   console.log(req.params[0]); 
});

// GET /pairs/testing/this/route
// Output: testing/this/route

Once you have the params you can then split on / which will give you an array of all the arguments passed to the route.

For more info on express routing take a look at this page.

As an alternative to splitting the arguments manually (which is probably the best solution), you can also define a route with a maximum allowed number of arguments, each one being optional:

app.get('/pairs/:arg1?/:arg2?/:arg3?/:arg4?', ...)

(to allow, at most, 4 arguments)

The results would be:

/pairs/USD
{ arg1: 'USD', arg2: undefined, arg3: undefined, arg4: undefined }

/pairs/USD/EUR
{ arg1: 'USD', arg2: 'EUR', arg3: undefined, arg4: undefined }

/pairs/USD/EUR/RUB
{ arg1: 'USD', arg2: 'EUR', arg3: 'RUB', arg4: undefined }

/pairs/USD/EUR/RUB/BTC
{ arg1: 'USD', arg2: 'EUR', arg3: 'RUB', arg4: 'BTC' }

You can use Regex for handling all such requests you can visit ExpressJs Documentation for more details

app.get('/pairs/*', function(req, res, next) {
    // app logic
});
发布评论

评论列表(0)

  1. 暂无评论