带或不带参数的express.js路由

时间:2018-05-07 11:34:37

标签: node.js express routes

我使用node.js v8.11.1并表达4.16.3。

说我有以下路线

R

我想做点什么

app.get('/:id', function(req, res){

所以,我可以去if(req.params.id) then query1 else //no id param in the url query2 http://localhost:3000/,路线会相应地做出回应。

但是当我转到http://localhost:3000/504时,我得到http://localhost:3000/

如何修复路线?

由于

2 个答案:

答案 0 :(得分:4)

使用?运算符使您的路由参数可选。

通过以下方式更改路线:

app.get('/:id?', function(req, res){

现在它应该适用于:http://localhost:3000/http://localhost:3000/504

答案 1 :(得分:2)

我同意@ n32303,你可以这样做:

app.get('/', function(req, res){
   //Called when there is no id specified
}
app.get('/:id', function(req, res){
   // Called when an Id is specified (req.params.id will be set )
}

消除对if语句的需要