【发布时间】:2012-12-06 04:27:53
【问题描述】:
我正在使用 express 开发一个简单的网站。 我只是对如何在渲染任何页面之前让 nodejs 检查会话感到困惑,这样如果用户没有登录,他就看不到任何东西。
我认为在 Rails 中这很简单,只需在应用程序控制器中添加一些代码即可。但是如何在 nodejs 中处理这样的事情呢?
【问题讨论】:
我正在使用 express 开发一个简单的网站。 我只是对如何在渲染任何页面之前让 nodejs 检查会话感到困惑,这样如果用户没有登录,他就看不到任何东西。
我认为在 Rails 中这很简单,只需在应用程序控制器中添加一些代码即可。但是如何在 nodejs 中处理这样的事情呢?
【问题讨论】:
定义一个中间件函数以在您的路由之前检查身份验证,然后在您的每个路由上调用它。例如在您的 app.js 中
// Define authentication middleware BEFORE your routes
var authenticate = function (req, res, next) {
// your validation code goes here.
var isAuthenticated = true;
if (isAuthenticated) {
next();
}
else {
// redirect user to authentication page or throw error or whatever
}
}
然后在你的路由中调用这个传递这个方法(注意 authenticate 参数):
app.get('/someUrl', authenticate, function(req, res, next) {
// Your normal request code goes here
});
app.get('/anotherUrl', authenticate, function(req, res, next) {
// Your normal request code goes here
});
【讨论】:
authenticate 泄漏到全球范围内。使用var 或只写function authenticate(req, res, next) { ... 以保持其范围为模块。
app.use而不是在路由处理程序中。 (当然,现在您必须确保您的函数跳过对登录页面及其相关资源的检查,这可能会很棘手。)
authenticate?