nodejs,如何检查每个页面上是否定义了会话

我正在使用快递开发一个简单的网站。 在渲染任何页面之前,我只是对如何进行nodejs检查会话感到困惑,所以如果用户没有login,他什么也看不到。

我认为在rails中是非常简单的,只需在应用程序控制器中添加一些代码即可。 但是如何在nodejs中处理这样的事情呢?

定义一个中间件function来检查路由之前的身份validation,然后在每个路由上调用它。 例如在你的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 });