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

Is it possible in express JS to only accept one of two values in a path variable?

Let’s say I have this GET url in my REST service:

router.get('/api/platform/:type', async (req, res) => {
    // something
}

I only want the request if :type is "windows" or "android". are there any way to do this in the url definition?

I think I’ve seen something like this before:

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

router.get('/api/platform/:type{windows|android}', async (req, res) => {
    // something
}

Something like that but it doesn’t quite work for me.

>Solution :

You can append a regular expression in parentheses to a route parameter to validate its format:

router.get('/api/platform/:type(windows|android)', async (req, res) => {
    // something
}

To have more control over the exact string that can be matched by a route parameter, you can append a regular expression in parentheses (()):

Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}

https://expressjs.com/en/guide/routing.html

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