我正在使用 Express,我想将 /
和 /index
匹配到相同的路由。但是如果我写
app.route('/(index)?')
Node 抛出这个错误:
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
at new RegExp (native)
at pathtoRegexp (c:\myproject\node_modules\express\node_modules\path-to-regexp\index.js:69:10)
at new Layer (c:\myproject\node_modules\express\lib\router\layer.js:32:17)
at Function.proto.route (c:\myproject\node_modules\express\lib\router\index.js:482:15)
at EventEmitter.app.route (c:\myproject\node_modules\express\lib\application.js:252:23)
at c:\myproject\server.js:28:19
at Array.forEach (native)
at Object.<anonymous> (c:\myproject\server.js:27:18)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
请注意,如果我使用
app.route('/foo(bar)?')
工作正常...
最佳答案
问号用于可选路由参数,而不是可选路由段。例如:
app.route('/:myVar?');
使用 app.route('/(index)?');
你匹配的路由实际上是 "http://myapp.com/(index)"
.
你想要一个正则表达式路由。
app.route(/^\/(index)?$/);
^
- 匹配一行的开头,因此整个表达式必须从开头匹配。\/
- 是一个转义的正斜杠,所有快速路由处理程序通常都以它开头。(index)?
- 现在可以按预期工作,因为它是一个正则表达式。括号中的内容因为有问号所以是可选的。$
- 匹配行尾,因此整个表达式必须一直匹配到行尾。
如果您省略 ^
和 $
那么正则表达式引擎将尝试将您的表达式与您的路由的子字符串进行匹配,这比检查整个url 字符串匹配,它可能会导致您不一定期望的路由匹配。感谢@robertkelp 的建议。
关于javascript - 使用 Express 的路由路径匹配 `/` 和 `/index`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30922680/