geo*_*per 2 javascript routes node.js express
我试图在快递中使用用户名作为路线,以查看他们的个人资料.
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();
}
});
});
Run Code Online (Sandbox Code Playgroud)
users.get_user是一个从db获取用户的函数.如果找不到用户,则继续下一个路线.我也有很多其他页面,比如/start,/forum等等.这是不够的做法,因为每次通过/:username路径时都会调用db .我的问题是,有更好的方法吗?
尝试定义具体路由(例如/start,/forum在之前),/:username在应用程序的路线.Express按照您定义的顺序匹配路由.
例如,这样做:
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
app.get('/:username', function(req, res, next) {...});
Run Code Online (Sandbox Code Playgroud)
不
app.get('/:username', function(req, res, next) {...});
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
Run Code Online (Sandbox Code Playgroud)
这样,如果用户进入/start,它将不会命中/:username路由并导致数据库命中.
| 归档时间: |
|
| 查看次数: |
903 次 |
| 最近记录: |