Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use parameters containing a slash character?

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?

like image 615
MarcoS Avatar asked Jan 02 '16 23:01

MarcoS


2 Answers

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.
like image 196
Amit Avatar answered Oct 10 '22 16:10

Amit


You can use this if your parameters has containing slashes in it

app.get('/getPersonByKey/:key(*)', function(req, res) { ... })

It works for me (at least in Express 4). In my case, I used parameters like ABC1/12345/6789(10).
Hopefully this useful.

like image 37
Utomoadito Avatar answered Oct 10 '22 17:10

Utomoadito