MrOnlineCoder MrOnlineCoder - 2 months ago 13
Javascript Question

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?

Answer

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.

Comments