【问题标题】:Navigation using express and EJS使用 express 和 EJS 进行导航
【发布时间】:2017-10-02 18:48:49
【问题描述】:

在弄清楚如何有效地在 EJS 页面之间导航时遇到问题:

文件目录:

我想从我的 index.ejs 页面转到 about.ejs 页面。这是我的 index.ejs 页面的代码,目前无法正确导航:

index.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
<body>
<h1> <a href="about.ejs"> This is a link to about page</a></h1>
</body>
</html>

app.js 服务器:

const express = require("express");
const path = require('path');
const app = express();

app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs")

app.get("/", (req, res) => {
res.render("index")
});

app.use(express.static('public'));

app.listen(3000);

我可以在 href 中输入什么来正确引用动态 about.ejs 文件? 我已经知道我可以从我的公用文件夹中引用静态文件,但我想引用动态 ejs 文件夹。如果不可能,任何提供相同功能的解决方案也可以。

【问题讨论】:

    标签: javascript node.js express ejs


    【解决方案1】:

    您应该渲染 about.ejs 模板以在客户端上使用它。为此,您需要创建一条新路线:

    app.get("/about", (req, res) => {
      res.render("about");
    });
    

    要打开它,请使用/about 路径。

    【讨论】:

      【解决方案2】:

      您的链接应指向/about。 然后你必须选择。 1)在您的服务器中具有服务该页面的功能。 2) 动态地提供您的页面。

      1.

      app.get("/about", (req, res) => {
        res.render("about")
      });
      

      2.

      app.get("/:page", (req, res) => {
        res.render(req.params.page);
      });
      

      【讨论】:

        【解决方案3】:

        你需要为你的 about 页面创建一个路由

        app.get("/about", (req, res) => {
            res.render("about")
        });
        

        并从超链接中删除扩展名。超链接应该是:

        <a href="/about">About</a>
        

        【讨论】:

          【解决方案4】:

          请注意第 7 行 index.ejs 中的更正

          <!DOCTYPE html>
          <html>
            <head>
             <title></title>
            </head>
          <body>
            <h1><a href='/about'> About</a></h1>  //there's no point including the ".ejs" extension at the end of the "about"
          </body>
          </html>
          

          在您的 app.js 服务器中,还要注意添加了(关于路由)。

          const express = require("express");
          const path = require('path');
          const app = express();
          
          app.set("views", path.resolve(__dirname, "views"));
          app.set("view engine", "ejs")
          
          app.get("/", (req, res) => {
          res.render("index")
          });
          
          app.get('/about', (req, res)=>{    //here you can include a new "about" route that should take you to the "about" page
              res.render('about')
          });
          
          app.use(express.static('public'));
          
          app.listen(3000);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-03-12
            • 1970-01-01
            • 1970-01-01
            • 2013-08-05
            • 2020-10-22
            • 2012-05-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多