使用express和EJS导航

有一个问题搞清楚如何有效地浏览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中input什么来正确引用dynamic的about.ejs文件? 我已经知道我可以从我的公共文件夹引用静态文件,但我想引用dynamicejs文件夹。 如果不可能的话,任何提供相同function的解决scheme也都可以。

您应该呈现 about.ejs模板以在客户端上使用它。 要做到这一点,你需要创build一个新的路线:

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

打开它使用/aboutpath。

你的链接应该指向/about 。 那么你必须select。 1)在您的服务器中有一个function来提供该页面。 2)dynamic提供你的页面。

1。

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

2。

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

您需要为您的关于页面创build路线

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

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

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

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