Multiple optional route parameters in Express?

廉价感情. 提交于 2019-12-02 21:52:51

The expressjs's guide to routing mentions:

Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.

Basically, you can use the ? character to make the parameter optional.

/articles/:year?/:month?/:day?
R. Gulbrandsen

Edited for own purpose of having the 3 different options in one answer. Credit to @hjpotter92 for his regex answer.

With URL Params

With regex

app.get('/articles/:year?/:month?/:day?', function(req, res) {
  var year = req.params.year; //either a value or undefined
  var month = req.params.month;
  var day = req.params.day;
}

Without regex

var getArticles = function(year, month, day) { ... }

app.get('/articles/:year', function(req, res) {
  getArticles(req.params.year);
}
app.get('/articles/:year/:month', function(req, res) {
  getArticles(req.params.year, req.params.month);
}
app.get('/articles/:year/:month/:day', function(req, res) {
  getArticles(req.params.year, req.params.month, req.params.day);
}

Define the 3 paths you want to support and reuse the same function

With Query Params

app.get('/articles', function(req, res) {
  var year = req.query.year; //either a value or undefined
  var month = req.query.month;
  var day = req.query.day;
}

The url for this endpoint will look like this:

http://localhost/articles?year=2016&month=1&day=19
nayebare

This type of route is not likely to work because of the underscores in the parameters passed.

app.get('/products/:product_Id/buyers/:buyer_Id', function(req, res) {
  getArticles(req.params.product_Id, req.params.buyer_Id);
}

So i suggest you use the following route system if the route is not working. There you will be able to send multiple parameters.

app.get('/products/:productId/buyers/:buyerId', function(req, res) {
  getArticles(req.params.productId, req.params.buyerId);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!