繁体   English   中英

如何让多条路线使用express.js中的同一条路线函数

[英]How to have multiple routes use the same route function in express.js

我可以用

app.get('/:someVar/xxxxx', function(req, res) { /* etc */ });

通过req.params.someVar获得req.params.someVar 但是,我希望www.example.com/12345/xxxxxwww.example.com/xxxxx都进入同一个app.get

我应该如何解决这个问题?

不要重复自己。 将数组传递给express.js的route方法:

app.route(["/12345/xxxxx", "/xxxxx"])
   .get(function (req, res) { /* etc */ })

请参阅app.routeapp.get

将函数分配给变量

var yourFunction = function (req, res) {
...
}

然后可以将其用作传递给app.get()参数

app.get('/:someVar/xxxxx', yourFunction);
app.get('/xxxxx', yourFunction);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM