简体   繁体   中英

Variable number of route params in express?

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
});

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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