Im trying to use the username as route in expressjs, to view their profile.
app.get('/:username', function (req, res, next) {
users.get_user(req.params.username, function (err, results) {
if(results[0]) {
res.render('/profile', {
title: 'Profile',
userinfo: results[0]
});
} else {
next();
}
});
});
users.get_user
is a function wich gets the user from the db. If it doesn't find a user it goes on to the next route. I also have a lot of other pages like /start
, /forum
etc. Is this an insufficient way of doing this, because theres a call to the db each time it passes through the /:username
route. My question is, is there a better more sufficient way?
Try defining the more specific routes (e.g. /start
, /forum
) before the /:username
route in your application. Express matches routes in the order that you define them.
E.g. Do this:
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
app.get('/:username', function(req, res, next) {...});
Not
app.get('/:username', function(req, res, next) {...});
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
This way, if the user goes to /start
, it won't hit the /:username
route and cause a database hit.