Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS route regex

I have route:

app.get('/:id', routes.action);

It works fine, but I need skip robot.txt and other (humans ....) I create regex (only chars or number):

/^[a-z]{0,10}$/

How I can route only ids, which match this regex?

like image 409
user1657173 Avatar asked Sep 08 '12 19:09

user1657173


3 Answers

Put the regex in parentheses like this:

app.get('/:id(^[a-z]{0,10}$)', routes.action);
like image 177
JohnnyHK Avatar answered Oct 18 '22 09:10

JohnnyHK


If you want to avoid a route matching a static file that exists physically, simply put the static middleware before the call to the app.router.

Then the static file (such as robots.txt) will be delivered and these calls will not get through to your routing.

Problem solved ;-).

like image 4
Golo Roden Avatar answered Oct 18 '22 09:10

Golo Roden


Internally, the strings that you give to the Express router are just converted into regexes anyway. If you look at the code, you can see that you can just pass a regex directly.

app.get(/^\/[a-z]{0,10}$/, routes.action);

The docs also have examples.

like image 2
josh3736 Avatar answered Oct 18 '22 09:10

josh3736