salep
salep

Reputation: 1380

Express.js conditional router.all()

I don't understand why urls starting with 2016 don't work. It just loads forever.

main (/), admin (/admin/*) and /home work without an issue.

function stringStartsWith(string, prefix) {
  return string.slice(0, prefix.length) == prefix;
}

router.get('/', csrfProtection, indexOnly, indexController.index);

router.get('/admin', adminOnly, adminController.index);

router.all('/*', function(req, res, next) {
  if (req.originalUrl == '/home') {
    next();
  } else if (stringStartsWith(req.originalUrl, "/admin")) {
    router.all('/admin/*', function(req, res, next) {
      if (req.originalUrl == '/admin') {
        next(); // it doesn't do anything, just allows the route above to work (admin welcome page.)
      } else {
        res.sendFile(path.resolve('views/backend/index.html'));
      }
    });
  } else if (stringStartsWith(req.originalUrl, "/2016")) {
    router.all('/2016/*', function(req, res, next) {
      res.sendFile(path.resolve('views/frontend/index/index.html'));
    });
  } else {
    res.sendFile(path.resolve('views/frontend/index.html'));
  }
});

Upvotes: 1

Views: 1011

Answers (1)

spiderman
spiderman

Reputation: 299

why do you put the 2016 route inside other route? it should simply be another route like the others:

function stringStartsWith(string, prefix) {
  return string.slice(0, prefix.length) == prefix;
}

router.get('/', csrfProtection, indexOnly, indexController.index);

router.get('/admin', adminOnly, adminController.index);

router.all('/2016/*', function(req, res, next) {
    res.sendFile(path.resolve('views/frontend/index/index.html'));
});

router.all('/*', function(req, res, next) {
  if (req.originalUrl == '/home') {
    next();
  } else if (stringStartsWith(req.originalUrl, "/admin")) {
    router.all('/admin/*', function(req, res, next) {
      if (req.originalUrl == '/admin') {
        next(); // it doesn't do anything, just allows the route above to work (admin welcome page.)
      } else {
        res.sendFile(path.resolve('views/backend/index.html'));
      }
    });
  } else {
    res.sendFile(path.resolve('views/frontend/index.html'));
  }
});

Upvotes: 1

Related Questions