如何在Express中使用参数渲染路线中的模板? [英] How to render template in route with params in Express?
问题描述
我正在使用Express和Pug模板引擎.我有两条路线:
I am using Express and Pug template engine. I have two routes:
/个人资料,其中显示已登录的用户个人资料信息.只能由登录用户访问
/profile which shows logged in user profile info. Can be accessed only by logged in users
/profile/:id ,显示其他用户的信息.每个人都可以访问.
/profile/:id which shows other user's info. Can be accessed by everyone.
这是我的代码:
app.get("/profile/:id", function(req,res) {
// Get info from DB for specifed username in req.params.id
res.render("profile.pug", locals);
});
app.get("/profile", isLoggedIn, function(req,res) { // isLoggedIn is middleware which checks if user is logged in
res.render("profile.pug", locals);
});
我使用express.static服务我的JS/CSS/图像:
I serve my JS/CSS/images using express.static:
app.use(express.static(__dirname+"/public"));
当我浏览/profile 时,一切正常,但是当我尝试/profile/:id 时,它将呈现没有样式的模板. Morgan loggger写道/profile/:id 试图不是从域根目录而是从/profile获取资产!
When I browse /profile, everything is OK, but when I try /profile/:id, it renders template without styles. Morgan loggger wrote that /profile/:id tries to get assets not from domain root, but from /profile!
GET /profile/css/bootstrap.css 404 7.352 ms
应为:
GET /css/bootstrap.css 200 7.352 ms
该如何解决?
推荐答案
最好为此类静态文件定义其他路由.
It is better to define another routes for such static files.
app.use("/static", express.static(path.resolve('./public/assets')));
然后将所有css文件放置在Assets文件夹下.之后,您可以在模板文件中使用"/static/css/bootstrap.css".
Then you place all the css files under assets folder. After that you can use '/static/css/bootstrap.css' in the template files.
我在您的代码中假设的问题是它将Profile/:id作为当前路径.
The problem I assume in your code is that it is taking profile/:id as current path.
这篇关于如何在Express中使用参数渲染路线中的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!