node.js - Express:逻辑或路由中

标签 node.js regex express

如何在 Express (v4.15) 路由中指定带有 OR 条件的正则表达式?

我希望以下路由指向相同的方法

/video/:videoId
/movies/:videoId
/media/:videoId

当我尝试时

app.get('/(video|media|movies)/:videoId', this.redirectToVideo.bind(this));

我收到以下错误

SyntaxError: Invalid regular expression: /^\/(?(?:([^\/]+?))|media|movies)\/(?:([^\/]+?))\/?$/: Invalid group

当我尝试不使用 () 时

app.get('/video|media|movies/:videoId', this.redirectToVideo.bind(this));

前两条路线有效,但那一条不行

 /media/:videoId

谢谢

最佳答案

我只会为你的路线使用一个数组:

app.get(['/video/:videoId', '/movies/:videoId', '/media/:videoId'], this.redirectToVideo.bind(this))

编辑:

如果您想使用正则表达式,这也可以:

app.get('(\/video|\/media|\/movies)/:videoId', this.redirectToVideo.bind(this)))

关于node.js - Express:逻辑或路由中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47078537/

相关文章:

mysql - HapiJS-MySQL : Query successful but postman returns Internal server error

PHP ereg 与 preg

node.js - 快速停止工作 - 未定义实用程序

node.js - Node express 与 OpenID 连接

node.js - 最佳实践 : Folder structure for client and server using create-react-app

node.js - 加载共享库 libnode.so.72 时出现 Node 错误

node.js - 如果 MongoDB 中已存在索引,则忽略 Mongoose 模式中的过期设置

regex - 非常大的文件之间的 Grep 模式匹配太慢了

regex - 尝试提取单元格中特定值之后的单词

node.js - Nginx 使用 ng-flow 和 Express (Node.js) 挂起请求