简体   繁体   中英

Is there a way to check if user is logged in using express.Router middleware?

How can I insert isLoggedIn as a condition to the get request using router.route?

const controller = require('./controller');
const Router = require('express').Router;
const router = new Router();

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  res.redirect('/');
}

router.route('/')
  .get((...args) => controller.find(...args))

I assume that the ...args are (req, res, next) I tried

router.route('/')
      .get(isLoggedIn(...args) => controller.find(...args))

But I get

.get((isLoggedIn(...args)) => controller.find(...args))
                ^
SyntaxError: Unexpected token (

The docs say, that you can assign multiple handlers to one route. Like this:

app.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

Source

In your case the coding looks like the following

router.get('/', isLoggedIn, controller.find);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM