Express.js条件router.all()

时间:2016-01-28 21:08:23

标签: node.js express

我不明白为什么从2016年开始的网址不起作用。它只会永远加载。

(/),管理员(/admin/*)/home无问题地工作。

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'));
  }
});

1 个答案:

答案 0 :(得分:1)

为什么将2016年航线置于其他航线内?它应该像其他路线一样简单:

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'));
  }
});