ThinkNewDev
ThinkNewDev

Reputation: 668

Dynamic Parameters for NodeJS Routes

I have a route that can be defined as

app.route('/api/*/*/*')

.get(function(req, res){
    var entitya = req.params['0'];
    var entityb = req.params['1'];
    var entity3 = req.params['2'];
})

.post(function(req, res){
    res.send('some stuff here');
});

This works good if I pass all three parameters but if I do the post route without any parameters it can't find it or if I go to the get route without all three defined it won't find the url.

Is there a way I can leave off the *'s in the route definition and make the get parameters dynamic? So if I have need to pass 3 parameters I can, or 2, or even 5?

Thanks!

Upvotes: 1

Views: 4365

Answers (2)

Sultan Aslam
Sultan Aslam

Reputation: 6238

You can use variables in URL and get them on express from req.query object. For example:

URL

/api/endpoint?entitya=a&entityb=ab&entity3=123

Route

app.route('/api/endpoint');

And get them from req.query.

BUT due to any reason you have to use params, here is an easy way

route is

app.route('/api/*')

and an array to get all dynamic params

const entity = req.params['0'] ? req.params['0'].split('/') : [];

Upvotes: 0

vodolaz095
vodolaz095

Reputation: 6986

you can bind routers for different API urls.

something like this

app.use('/api/v1/function1', router1);
app.use('/api/v1/function2', router1);

or, you can use regexes as URL name

app.get( /^\/api\/([a-z0-9]+)\/([a-z0-9]+)$/, function(req,res) {
   req.params[0]; //first match of reges
   req.params[1]; //second match of reges
});

app.post( /^\/api\/([a-z0-9]+)\/([a-z0-9]+)$/, function(req,res) {
   req.params[0]; //first match of reges
   req.params[1]; //second match of reges
});

Upvotes: 1

Related Questions