Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic url segments with ExpressJS

When I needed to add a dynamic segment to the URL, the first thing that came to mind was to try the following:

app.get('/one/*/two/*/three', (req, res, next) => {
    // req.params as any)[0] - first dynamic segment
    // req.params as any)[1] - second dynamic segment
});

Turns out, the code above works perfectly. What confuses me, however, I cannot find it anywhere in the official documentation, and any answer here about dynamic segments with ExpressJS suggests different things, none of them suggest use of asterisks.

Am I doing something wrong here? Or what am I missing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the official documentation about Routing:

Route paths

Route paths, in combination with a request method, define the
endpoints at which requests can be made. Route paths can be strings,
string patterns, or regular expressions.

The characters ?, +, *, and () are subsets of their regular expression
counterparts. The hyphen (-) and the dot (.) are interpreted literally
by string-based paths.

And:

This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so
on.

app.get('/ab*cd', (req, res) => {   res.send('ab*cd') })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading