javascript - Using Express' route paths to match `/` and `/index` -


i'm using express , want match / , /index same route. if write

app.route('/(index)?') 

node throws error:

c:\myproject\node_modules\express\node_modules\path-to-regexp\index.js:69   return new regexp(path, flags);          ^ syntaxerror: invalid regular expression: /^\/(?(?:([^\/]+?)))?e\/?$/: invalid group     @ new regexp (native)     @ pathtoregexp (c:\myproject\node_modules\express\node_modules\path-to-regexp\index.js:69:10)     @ new layer (c:\myproject\node_modules\express\lib\router\layer.js:32:17)     @ function.proto.route (c:\myproject\node_modules\express\lib\router\index.js:482:15)     @ eventemitter.app.route (c:\myproject\node_modules\express\lib\application.js:252:23)     @ c:\myproject\server.js:28:19     @ array.foreach (native)     @ object.<anonymous> (c:\myproject\server.js:27:18)     @ module._compile (module.js:460:26)     @ object.module._extensions..js (module.js:478:10) 

note if use

app.route('/foo(bar)?') 

it works fine...

the question mark optional route parameters, not optional route segments. example:

app.route('/:myvar?'); 

with app.route('/(index)?'); matching routes literally "http://myapp.com/(index)".

you want regular expression route.

app.route(/^\/(index)?$/); 
  • ^ - matches beginning of line, whole expression must match beginning.

  • \/ - escaped forward slash, express route handlers start with.

  • (index)? - works expect because it's regular expression. contents of parenthesis optional because of question mark.

  • $ - matches end of line, whole expression must match way end.

if omit ^ , $ regular expression engine try match expression against substrings of route bit more expensive checking if entire url string matches, , lead route matches didn't expect. @robertkelp suggestion.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -