【发布时间】:2013-03-13 08:19:38
【问题描述】:
给定一个 nodejs、mongoose、mongodb、expressjs 设置,我们拥有验证特定请求的权限/安全相关路由。例如:
permissionUtils.checkStudentWritePermissions = function(req, res, next){
//load this student from the mongoose db
//ensure the current user has permission to update this student
}
server.put("/api/student/:studentId/enroll",
permissionUtils.checkStudentWritePermissions, function(req, res, next){
//load student from the database, validate the changes
//update student in mongodb, send new version back to user
});
中间件很有用,因为我们确保当前用户在任何情况下都有权更新学生。 (代码重用等)您会注意到,在这两个示例中,我都是从 mongodb 加载学生。是否有一种可接受的模式来避免这种双重加载?某种请求周期缓存或传递模型的巧妙方式?
【问题讨论】:
-
我通常从中间件向 res.locals 添加东西。就像
res.locals.student = user;一样,你的最终函数可以在 res.locals 中查找——这也会将其暴露给响应/模板对象。