Express.Router中间件在路由注册后在所有路由上被调用

时间:2018-03-07 14:21:42

标签: node.js express express-router

我有一个简单的应用程序,它有一个登录页面和一个经过身份验证的用户部分,未经身份验证的用户将被重定向回登录。在我所有路线的末尾,我有app.all('*', ...),它返回404错误页面。

当我通过身份验证后,一切正常,但如果我退出并尝试获取未使用的路由,我将被重定向到登录页面而不是获得404响应。

据我所知,这是因为我添加了处理重定向的中间件,但我希望它只适用于在一个确切的路由器中指定的路由 - 而不是在中间件之后放置的所有路由(甚至是应用级别的路由器)

我目前看到的唯一解决方案是在每个受限制的路由中使用此authCheck中间件,而不是使用router.use全局注册它,但我仍然想知道是否有更好的方法?

const express = require('express')

module.exports = (app) => {
  const authRouter = express.Router()

  // ================================
  // ========= Public Routes ========
  // ================================
  app.get('/login', () => { /* ... login route */ })
  app.post('/login', () => { /* ... login route */ })

  // ====================================
  // ========= Restricted Routes ========
  // ====================================
  authRouter.use((req, res, next) => {
    req.isAuthenticated()
      ? next()
      : res.redirect('/login')
  })

  authRouter.get('/', () => { /* restricted route */ })

  // register restricted routes
  app.use(authRouter)

  // ========================================
  // ============ Other routes ==============
  // ========================================

  // error 404 route <--- this works only for authenticated users
  app.get('*', (req, res) => {

    res.status(404)
    res.render('error404')
  })
}

感谢任何想法..

3 个答案:

答案 0 :(得分:0)

试试这个,你可以创建一个没有auth的所有URL的数组,并检查中间件。

const authMiddleware = (req, res, next) => {
    /* Urls Without Auth */
    const withoutAuth = ['/login'];
    if (withoutAuth.includes(req.url) || req.isAuthenticated()) {
        next();
    } else {
        res.redirect('/login');
    }
};

app.use(authMiddleware);

答案 1 :(得分:0)

const express = require('express')
// Note: FWIW I think it's better to organize your middleware
// into separate files and store them into separate directory
// So you could use it like that:
// const verifyAuthMiddleware = require('./middleware/verifyAuthMiddleware);
const verifyAuthMiddleware = (req, res, next) => {
    req.isAuthenticated()
      ? next()
      : res.redirect('/login')
  };

module.exports = (app) => {    
  // ================================
  // ========= Public Routes ========
  // ================================
  app.get('/login', () => { /* ... login route */ })
  app.post('/login', () => { /* ... login route */ })

  // ====================================
  // ========= Restricted Routes ========
  // ====================================    
  // You can add the middleware like that
  app.get('/', [verifyAuthMiddleware], () => { /* restricted route */ });

  // Or you can add a middleware to a group of routes like that
  app.use('/user', [verifyAuthMiddleware]);
  // And then every route that starts with "/user" uses the middleware
  app.get('/user/settings', () => {});
  app.get('/user/wallet', () => {});
  app.get('/user', () => {});
  app.post('/user/wallet', () => {});
  // etc


  // ========================================
  // ============ Other routes ==============
  // ========================================

  // error 404 route <--- this works only for authenticated users
  app.get('*', (req, res) => {

    res.status(404)
    res.render('error404')
  })
}

答案 2 :(得分:0)

谢谢你的回复。最后,我这样做了:

function authCheck (req, res, next) {
    return req.isAuthenticated()
        ? next()
        : res.redirect('/login')
}

// Product routes
const prodRouter = express.Router()
prodRouter.get('/', products.getlist)
prodRouter.get('/:uuid/:tab?', products.getbyId)
prodRouter.post('/:uuid/:tab?', products.update)

// Register product routes
app.use('/products', [authCheck, prodRouter])

// For all other routes return 404 error page
app.get('*', (req, res) => {
    res.status(404).render('error404')
})

通过这种方法,authCheck中间件仅在/product路由上使用,因此当我访问/missing-page时,我正确地Error 404 page

相关问题