I have a route built up like this in different files.
I need one of the routes to respond to all of these extensions (including no extension):
/api/sitemap
/api/sitemap.xml
/api/sitemap.html
/api/sitemap.json
my unmounted route definition for the sitemap route looks like this:
router.route('/\.:ext?');
But the only path this one responds to is /api/sitemap. It does not accept any of the aforementioned extensions. In fact, it does not respond to any extensions at all.
Here's the buildup of my routes in condensed form:
/
/api
/api/sitemap (pattern should accept sitemap.xml sitemap.json or sitemap.html)
root-routes.js
const apiRoutes = require('./api-routes.js');
const router = require('express').Router();
const mainRoot = router.route('/');
mainRoot((req, res) => { res.status(200).send('ok') };
router.use('/api', apiRoutes);
module.exports = router;
api-routes.js
const sitemapRoutes = require('./sitemap-routes.js');
const router = require('express').Router();
const apiRoot = router.route('/');
apiRoot((req, res) => { res.status(200).send('ok') };
router.use('/sitemap', sitemapRoutes);
module.exports = router;
sitemap-routes.js
const router = require('express').Router();
const sitemapRoot = router.route('/\.:ext?');
sitemapRoot((req, res) => { res.status(200).send('ok') };
modules.exports = router;
I was able to match using another .use
for the route using the extension.
apiRouter.use("/sitemap", sitemapRouter);
apiRouter.use("/sitemap.:ext?", (req, res) => {
// sample response
res.end(`${req.params.ext ? req.params.ext : 'root'} did match!`);
});
I tried a bunch of things, but could only get the desired route matches doing this. If you need to keep all sitemap
related functions together, you should export
the router and the function needed for the /sitemap.:ext?
callback.
The other thing you can do is pass the app
object in to the router, but this isn't desirable.