Multiple optional route parameters in Express?

前端 未结 3 890
借酒劲吻你
借酒劲吻你 2021-01-31 07:07

I am using Express to handle a route which is in the format of /articles/:year/:month/:day, where year, month and day are optional.

  • If none of the thr
3条回答
  •  忘掉有多难
    2021-01-31 07:58

    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
    

提交回复
热议问题