Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express Routing: multiple URLs to the same route

Tags:

express

routes

I'm trying to make the multiple URLs work on a single express route. How can I make the following URLs all route to the same page?

  • https://example.com/page-slug-name
  • https://example.com/page-slug-name/amp
  • https://example.com
  • https://example.com/amp

It seems like this should work but it's not:

router.get("/:slug?(/amp)?", function(req, res, next) {

  if (!req.params.slug) {
    req.params.slug = 'home'
  }

  getData(slug, function(err, data){

    res.render('index', data)

  });

});
like image 938
jwerre Avatar asked Oct 27 '25 05:10

jwerre


1 Answers

You can have it in single express route by placing multiple URLS inside an array. In your case, this will be

  app.get(['/', '/:slug', '/amp', '/:slug/amp'], function(req, res, next) {
    if (!req.params.slug)
      req.params.slug = 'home'
    getData(slug, function(err, data){
      res.render('index', data)
    });
  );
like image 64
Mishhub Mohammed Avatar answered Oct 29 '25 05:10

Mishhub Mohammed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!