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

Asked

Viewed 245 times

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 parameter activities may have different names in different languages and there are other site routes that have 3 parameters.

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

1 answer

1


Express allows you to have a regex associated with a parameter.

using :activities(uma_regex) it will seek to match and if find passes this value to the req.params.activities.

An example would be:

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

Using the url /es/ocupaciones/golf can be picked up later on the object req.params the url parameters. It would be something like:

{ lang: 'es', activities: 'ocupaciones', activity: 'golf' }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.