0

Existing Code:

const express = require('express');
const router = express.Router();
router.get('/data/:d1/:d2/:d3', require('../apifoo').foo);

Route:
/data/:d1/:d2/:d3

Path:
/data/1/2/3

req.params :
'd1' :'1',
'd2': '2',
'd3': '3'

But what if the number of parameters is not known in advance? I tried to define these parameters dynamically by means of regular expression::

router.get(/\/data(\/\d+){1,}$/, require('../apifoo').foo);

RegExp:
/\/data(\/\d+){1,}$/

Path:
/data/1/2/3

req.params :
'0' : '/3'

Unfortunately it doesn't work! Is it possible to obtain the same 'req.params' like in example above, using RegExp or somewhat else?

Artem
  • 17
  • 1
  • 6

1 Answers1

0

You have to define specific route for handling request what you can do is you can make the param optional like below

router.get('/data/:d1?/:d2?/:d3?', require('../apifoo').foo);

so this route will work in case of /data/1 and in case of /data/1/2 and also in case of /data/1/2/3

Regex in route is only for restricting routes to accept params in certain format for more information visit this url https://expressjs.com/en/guide/routing.html

Anku Singh
  • 914
  • 6
  • 12