如何为未通过Expresslogin的用户实现默认路由?

使用Node.js和Express,我想让没有login的用户总是redirect到主页面。 什么是实现这个最简单的方法? 理想情况下,我不必向每条路线添加代码,检查是否有人login。

我很早以前在node上工作,但是它应该可以工作

function requireLogin(req, res, next) { if (req.session.loggedIn) { next(); // allow the next route to run } else { // require the user to log in res.redirect("/"); // or render a form, etc. } } // Automatically apply the `requireLogin` middleware to all // routes starting with `/` app.all("/*", requireLogin, function(req, res, next) { next(); // if the middleware allowed us to get here, // just move on to the next route handler }); 

这取决于你如何定义“未login”,但是说状态被存储在req.session 。 在这种情况下,您可以添加一个中间件,将未login的用户redirect到login页面:

 app.use(function(req, res, next) { if (req.path === '/loginpage') // pass requests for login page next(); else if (! req.session || req.session.isLoggedIn !== true) // check logged in status res.redirect('/loginpage'); // redirect to login page when not logged in else next(); // else just pass the request along }); app.get('/loginpage', function(req, res) { res.send('login page'); }); 

你可以使用像护照这样的东西,它使检查授权的路线要简单得多

 function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login') //Or whatever your main page is }; 

你现在可以像这样检查你的路线

 app.get('/account',ensureAuthenticated,routes.account);