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

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.


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.


That will enable you to do


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.

you can send data to view as follow:

//in the server side ...
 app.get('/search/:qkey/:qvalue', function(req, res){

and in the client side... call to ajax

  success: function(data){
    var string = eval("(" + data + ")");
    //you access to server response with
    console.log(string.qkey+" and "+ string.qvalue);

Need Your Help

OpenCV Java count objects in photo

java android opencv

I have a small image and a large image and i want to use OpenCV to count how often the large image contains the small image (irrespective of rotation and size).

Why won't this printf() statement print two string variables in C?

c string debugging printf

I have been researching like mad while I learning C. I have been debugging a C program and I thought I had some major issues here. Now I have critical issues. I made a dummy program to print two st...