15

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?

Amit
  • 45,440
  • 9
  • 78
  • 110
MarcoS
  • 17,323
  • 24
  • 96
  • 174

3 Answers3

23

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.
Amit
  • 45,440
  • 9
  • 78
  • 110
8

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.

Utomoadito
  • 239
  • 3
  • 3
0

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

This isn't working for me.

Swagger-ui will encode the path var before using it. e.g. article/2159 will become article%2F2159. When going directly with curl, it will not get encoded. the slash will remain a slash instead of %2F. And then the route is not matched.

Update: I'm on fastify. On express 4.X this works correctly.

user1231712
  • 31
  • 1
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Nikolai Kiselev Jun 12 '22 at 09:00