简体   繁体   中英

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 . However, I want both www.example.com/12345/xxxxx and www.example.com/xxxxx to go into the same app.get

How should I approach this problem?

Don't repeat yourself. Pass an array to express.js 's route method:

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

see app.route & app.get

Assign function to variable

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

And you can use it afterwards as parameter passed to app.get()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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