簡體   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