How to include a regex in the parameters of an Express route?

1

In a project I'm doing I want to point a specific route to a controller. In a simple case of a route with parameters I would do so:

app.get('/:lang/:activities/:activity', require('./routes/activities'));

But in this specific case the activities parameter can have different names in different languages and there are other routes of the site that have 3 parameters.

How can I combine variations of activities while maintaining functionality to be able to use req.param.activities in the controller?

    
asked by anonymous 28.05.2016 / 16:19

1 answer

1

Express allows you to regex associated with a parameter .

using :activities(uma_regex) it will try to match and if it finds it passes this value to req.params.activities .

An example would be:

app.get('/:lang/:activities(actividades|activities|ocupaciones)/:activity', require('./routes/activities'));

Using the url /es/ocupaciones/golf you can then search the object req.params for the url parameters. It would be something like:

{ lang: 'es', activities: 'ocupaciones', activity: 'golf' }
    
28.05.2016 / 16:19