How to render template in route with params in Express?

倾然丶 夕夏残阳落幕 提交于 2020-01-03 02:55:30

问题


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 which shows other user's info. Can be accessed by everyone.

Here is my code:

    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);
    });

I serve my JS/CSS/images using express.static:

app.use(express.static(__dirname+"/public"));

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

Which should be:

GET /css/bootstrap.css 200 7.352 ms

How to fix that?


回答1:


It is better to define another routes for such static files.

app.use("/static", express.static(path.resolve('./public/assets')));

Then you place all the css files under assets folder. After that you can use '/static/css/bootstrap.css' in the template files.

The problem I assume in your code is that it is taking profile/:id as current path.



来源:https://stackoverflow.com/questions/39305398/how-to-render-template-in-route-with-params-in-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!