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
3 Answers
Reset to default 11In 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
});