【问题标题】:Load different EJS, depending on URL根据 URL 加载不同的 EJS
【发布时间】:2016-10-21 08:12:18
【问题描述】:

如果 URL 包含“todos”,例如“.../todos/*”,他应该加载不同的 EJS 模板 (todos.ejs)。如果 URL 不包含 'todos',则会加载正常的 index.ejs。

我尝试了类似下面的方法,但我认为app.get 的使用是错误的。

if (req.url.indexOf("todos") >= 0) {
    app.get('/todos/*', function(req, res) {
        res.render('todos', {
            title: 'todos page'
        });
    });
} else {
    app.get('/', function(req, res) {
        res.render('index', {
            title: 'index page'
        });
    });
}

【问题讨论】:

    标签: javascript angularjs node.js express ejs


    【解决方案1】:

    应该是这样的。

    app.get('*', function(req, res) {
        if (req.url.indexOf("todos") >= 0) {
            return res.render('todos', {
               title: 'todos page'
            });
        } 
    
        res.render('todos', {
            title: 'todos page'
        });
    });
    

    【讨论】:

    • 你可以做 * 部分并在以后覆盖 todos 部分。
    【解决方案2】:

    试试这个

    app.get('*', (req, res) => {
      if (req.url.indexOf('todos') === -1) {
        return res.render('index', { title: 'index page'})
      } 
      else {
        return res.render('todos', { title: 'todos page' })
      }
    })
    

    【讨论】:

      【解决方案3】:

      您可以将regular expressions to match URL paths 与 Express 一起使用,所以:

      // Match any URL with '/todos/' in the path:
      app.get(/\/todos\//, function(req, res) {
        res.render('todos', { title: 'todos page' });
      });
      
      // Match the rest:
      app.get('*', function(req, res) {
        res.render('index', { title: 'index page' });
      });
      

      如果你不关心 "todos" 周围的斜线,匹配变成这样:

      app.get(/todos/, ...);
      

      请注意,声明路由处理程序的顺序很重要:您希望首先声明最具体的匹配(“todos”),最后声明最不具体的(“其余”)。

      【讨论】:

      • 感谢您提供干净的解决方案。它在一般情况下工作,但是......我一直使用/ 而不是*,这很有效。 使用*,express 或 ejs 存在外部脚本/样式表问题。比如<link ... href="css/style.css"/>我得到Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:1337/css/style.css".
      • @ChrisEbert 将再次取决于声明的顺序。如果您使用express.static() 来处理 JS/CSS,请确保在您的任何常规路由之前声明它。此外,您可能应该在 JS/CSS URL 中使用绝对路径(以 / 开头)。
      猜你喜欢
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2013-12-01
      • 2015-01-11
      • 2019-11-03
      相关资源
      最近更新 更多