Additional extension in express route

I want to have an optional extension, for example .xml or .csv or .json (by default, no extensions will return json).

 app.get('/days-ago/:days(.:ext)?', function(req, res) { 

This does not work, is there something I am doing wrong?

 GET /days-ago/7.xml GET /days-ago/7.csv GET /days-ago/7.json GET /days-ago/7 
+5
source share
2 answers

It seems that you are using the wrong template for the route. Here is the corrected one:

 app.get('/days-ago/:days\.:ext?', function(req, res) { 

Therefore, to achieve your goal, I would create middleware that checks an empty parameter and sets it to the desired

Something like that:

 var defaultParamMiddleware = function(req, res, next) { if (!req.params.ext) { req.params.ext = 'json'; } next(); }; app.get('/days-ago/:days\.:ext?', defaultParamMiddleware, function (req, res) { res.json(req.params); }); 
+6
source

Try a real regex: app.get(/\/days-ago\/\w+(\.\w+)?/), function (req, res {... (or the like). The built-in grammar of the route parameter parameter is rather limited Perhaps he will be able to express what you need, but I do not see the point when regular expressions are built into the language and understandable.

0
source

Source: https://habr.com/ru/post/1210377/


All Articles