[英]Expressjs routes with username
Im trying to use the username as route in expressjs, to view their profile. 我试图使用用户名作为expressjs中的路由,以查看其个人资料。
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. users.get_user
是从数据库获取用户的函数。 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. 我也有很多其他页面,例如
/start
, /forum
等。这是否是一种不足的方法,因为每次通过/:username
路由时都会有一个对db的调用。 My question is, is there a better more sufficient way? 我的问题是,是否有更好更好的方法?
Try defining the more specific routes (eg /start
, /forum
) before the /:username
route in your application. 尝试在应用程序中的
/:username
路由之前定义更具体的路由(例如/start
, /forum
)。 Express matches routes in the order that you define them. Express会按照您定义它们的顺序匹配路由。
Eg 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. 这样,如果用户转到
/start
,它将不会命中/:username
路由并导致数据库命中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.