node.js - Express.js 条件 router.all()

标签 node.js express

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

main (/)、admin (/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'));
  }
});

最佳答案

为什么要把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'));
  }
});

关于node.js - Express.js 条件 router.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35072061/

相关文章:

node.js - 是否有不需要使用浏览器的 Node.js 无浏览器 websocket 客户端?

javascript - express v4 : How do I run route-specific middleware before param middleware?

mysql - 如何在相关表中添加子行? (Sequelzie N :M Relationship)

node.js - 使用 Node 生成 API token - 大写、小写字母和数字?

jquery - MeteorJS 基本 jquery 使用

javascript - JSON 对象在 Node.js 帖子中被接收为未定义?

javascript - 如何用log4j或winston写入大量日志?记不清

node.js - NodeJS套接字挂起超时

node.js - 在 https 上从不同位置快速提供文件

javascript - 在expressJS中如何创建一个缓存,使多个请求等待同一个promise