1

使用 Node.js 和 Express,我想让未登录的用户始终重定向到主页。实现这一目标的最简单方法是什么?理想情况下,我不必在每条路由中添加代码来检查是否有人登录。

4

3 回答 3

2

It depends on how you define 'not logged in', but say that status is stored in req.session. In that case, you could add a middleware that will redirect not-logged-in users to a login page:

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');
});
于 2013-04-10T08:15:30.940 回答
1

You can user something like passport.It makes checking the authorized routes a lot simpler

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

You can now check your routes like this

app.get('/account',ensureAuthenticated,routes.account);
于 2013-04-10T08:14:37.243 回答
1

我很久以前在节点上工作,但它应该可以工作

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
});
于 2013-04-10T08:12:02.000 回答