Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js - Filter a number and a string in the URL

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)
like image 535
htaidirt Avatar asked Dec 01 '22 04:12

htaidirt


1 Answers

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.
}
like image 73
Jonathan Lonowski Avatar answered Dec 04 '22 03:12

Jonathan Lonowski