Some additional route options in Express?

I use Express to handle a route that is in the format /articles/:year/:month/:day , where year, month, and day are optional.

  • If none of the three parameters is specified, all articles will be returned;
  • If a year is given, the articles of that year will be returned;
  • If year and month are specified, articles of that year and month will be returned;
  • If all three parameters are specified, the articles of that year, month, and day will be returned.

My question is how to make them optional? With the current route, which I determined, if all three parameters are not present, it cannot be resolved and will fall into the default route.

+7
express routing
source share
2 answers

expressjs guide in routing messages:

Express uses path-to-regexp to match route routes; see the documentation for the regex path for all route definitions. Express Route Tester is a convenient tool for testing the main Express routes, although it does not support pattern matching.

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

 /articles/:year?/:month?/:day? 
+12
source share

Edited for your own purpose, have 3 different options in one answer. Thank @ hjpotter92 for his regular request.

URL Parameter

With regex

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

No 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 3 paths you want to support and reuse the same function

With request parameters

 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 
+7
source share

All Articles