4

I would like to know if it is possible to check a specific format (a Regex expression) of a Express.js URL query, in the query itself (without entring the callback.)

Concretely, I would like to perform a different action, depending on if the query URL is a string or a number (like a user id and user name):

app.get('/:int', function(req, res){
    // Get user info based on the user id.
}

app.get('/:string', function(req, res){
    // Get user info based on the user name.
}

Can I filter numbers in the first parameter of the app.get, or is it impossible except doing the test inside the callback:

/(\d)+/.test(req.params.int)
/(\w)+/.test(req.params.string)
AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
Hassen
  • 6,966
  • 13
  • 45
  • 65

2 Answers2

17

You can specify a pattern for a named parameter with parenthesis:

app.get('/:int(\\d+)', function(req, res){
    // Get user info based on the user id.
}

app.get('/:string(\\w+)', function(req, res){
    // Get user info based on the user name.
}
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • I wasn't aware that express could do that. What version has this been introduced in? – Floby Mar 05 '13 at 16:59
  • Great Jonathan. Can you provide us a link or the documentation to learn more. Thanks. – Hassen Mar 05 '13 at 17:05
  • It's not currently a well-documented feature, but you can find it in the source code: [`utils.pathRegexp(...)`](https://github.com/visionmedia/express/blob/3.1.0/lib/utils.js#L245-L282). The `capture` argument in the `replace` is how it's defined. – Jonathan Lonowski Mar 05 '13 at 17:10
3

the express router also accepts regexp as first argument.

app.get(/(\d+)/, function(req, res, next) {})
app.get(/(\w+)/, function(req, res, next) {})
Floby
  • 2,306
  • 17
  • 15
  • Thanks Floby, but how can I use the query parameter as a variable for my callback? In your solution, I can only filter a URL but not use the query value. – Hassen Mar 05 '13 at 17:00