0

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;
LongHike
  • 4,016
  • 4
  • 37
  • 76
  • do you need to capture and use the extension? – emran Aug 06 '18 at 16:44
  • what happens if you use `router.use('/sitemap*', sitemapRoutes);` with the `*` – emran Aug 06 '18 at 17:08
  • Yes, and I wish I wouldn't have to. – LongHike Aug 06 '18 at 17:12
  • @terminally-chill The wildcard would only be a last resort. I need at least two more routes under sitemap. And maybe even more. And then it becomes messy. – LongHike Aug 06 '18 at 17:18
  • I see what you mean. With the extension attached, it will not even enter the defined route. You can tell by using `router.use` as middleware within `sitemap-routes.js`. I think you might need to define a separate route in the `api-routes` module. – emran Aug 06 '18 at 17:49

1 Answers1

1

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.

emran
  • 902
  • 6
  • 12