使用express和EJS进行导航

时间:2017-10-02 18:48:49

标签: javascript node.js express ejs

有一个问题,想出如何有效地在EJS页面之间导航:

文件目录:

enter image description here

我想从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文件夹。如果不可能,任何提供相同功能的解决方案也会这样做。

4 个答案:

答案 0 :(得分:1)

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

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

要使用/about路径打开它。

答案 1 :(得分:1)

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

1

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

2

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

答案 2 :(得分:1)

您需要为约会页面创建路线

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

从超链接中删除扩展名。超链接应为:

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

答案 3 :(得分:0)

请注意第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);