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.
My question is, how do I make them optional? With the current route I've defined, unless all three parameters are present, it will not be able to be resolved and will fall into the default route.
Basically, you can use the ? character to make the parameter optional.
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req. params object, with the name of the route parameter specified in the path as their respective keys.
Express allow you to use a wildcard within a route path using * . For example, the path defined below can be access using anything that follows the base URL (for example, if you wanted to build a “catch all” that caught routes not previously defined). app. get('/*',function(req,res) { req. send("I am Foo"); });
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With