简体   繁体   中英

How to render template in route with params in Express?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM