[Fixed] How to use parameters containing a slash character?

Issue

My MongoDB keys in person collection are like this:

TWITTER/12345678
GOOGLE/34567890
TWITTER/45678901
...

I define getPersonByKey route this way:

router.route('/getPersonByKey/:providerKey/:personKey').
  get(function(req, res) { // get person by key
    var key = req.params.providerKey + '/' + req.params.personKey;
    // ...
  }
);

Of course I’d prefer to be able to write something like this:

router.route('/getPersonByKey/:key').
  get(function(req, res) { // get person by key
    var key = req.params.key;
    // ...
  }
);

But this doesn’t work, since GET http://localhost/getPersonByKey/TWITTER/12345678 of course results in a 404, since the parameter with the slash is interpreted as two distinct parameters…
Any idea?

Solution

Express internally uses path-to-regexp to do path matching.

As explained in the documentation, you can use a “Custom Match Parameter” by adding a regular expression wrapped in parenthesis after the parameter itself.

You can use the following path to get the result you need:

router.route('/getPersonByKey/:key([^/]+/[^/]+)').
  get(function(req, res) { // get person by key
    var key = req.params.key;
    // ...
  }
);

You can test and validate this or any other route here.

Leave a Reply

(*) Required, Your email will not be published