简体   繁体   English

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

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

I can use 我可以用

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

to get someVar by req.params.someVar . 通过req.params.someVar获得req.params.someVar However, I want both www.example.com/12345/xxxxx and www.example.com/xxxxx to go into the same app.get 但是,我希望www.example.com/12345/xxxxxwww.example.com/xxxxx都进入同一个app.get

How should I approach this problem? 我应该如何解决这个问题?

Don't repeat yourself. 不要重复自己。 Pass an array to express.js 's route method: 将数组传递给express.js的route方法:

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

see app.route & app.get 请参阅app.routeapp.get

Assign function to variable 将函数分配给变量

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

And you can use it afterwards as parameter passed to app.get() 然后可以将其用作传递给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