Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define complex routes with named parameters in express.js?

Tags:

express

I want to set up some more complex routes that can include a number of optional parameters. Preferably, I would like to use named parameters for ease of access. Here is an example of what I'm trying to achieve:

// The following routes should be matched based on parameters provided:
// GET /books/:category/:author
// GET /books/:category/:author/limit/:limit
// GET /books/:category/:author/skip/:skip
// GET /books/:category/:author/limit/:limit/skip/:skip
// GET /books/:category/:author/sort/:sortby
// GET /books/:category/:author/sort/:sortby/limit/:limit
// GET /books/:category/:author/sort/:sortby/skip/:skip
// GET /books/:category/:author/sort/:sortby/limit/:limit/skip/:skip
app.get('/books/:category/:author/(sort/:sortby)?/(limit/:limit)?/(skip/:skip)?', myController.index);

As you can see, I'm trying to group the optional parameters with (paramKey/paramValue)?. That way I was hoping to be able to "mix and match" the optional parameters while still making use of the parameter naming. Unfortunately, this doesn't seem to work.

Is there any way to get this working without having to write straight regular expressions and adding additional logic to parse any resulting index-based parameter groups?

Basically, I'm looking for an easy way to parse key/value pairs from the route.

like image 832
JWK Avatar asked May 15 '11 20:05

JWK


1 Answers

It looks like you want to re-implement the query string using the URL path. My guess is that if you really wanted that, yes, you would have to write your own parsing/interpreting logic. AFAIK express path parameters are positional, whereas the query string is not. Just use a query string and express will parse it for you automatically.

/books?category=sports&author=jack&limit=15?sortby=title

That will enable you to do

req.query.sortby

You may be able to get express to do 1/2 of the parsing for you with a regular expression path like (:key/:value)* or something along those lines (that will match multiple key/value pairs), but express isn't going to then further parse those results for you.

like image 157
Peter Lyons Avatar answered Sep 27 '22 20:09

Peter Lyons