将钩子应用于某些路由节点.js

Apply hook to certain routes Node.js

本文关键字:路由 节点 js 应用于      更新时间:2023-09-26

我正在使用Node.js构建一个应用程序。我编写了一个身份验证中间件,我希望将其应用于除/index 和/login 路由之外的所有路由。有没有办法防止钩子应用于我的/index 和/login 路由?我当前的代码:

我的app.js

var middleware = require('./methods/authentication.js');
app.use(middleware.authenticate) //this makes it apply to ALL routes

我的authentication.js

module.exports = {
authenticate: function(req, res, next) {
    var cookie = parseCookie.parseCookie(req.headers.cookie);
    user.returnUser(cookie, function(result) {
        if(result.length > 1) {
            next();
        } else {
            res.redirect('/login');
        }
    });
  }
}

任何建议将不胜感激...提前感谢!

您可以插入一个查看路由的填充程序,并且仅在路径不是您的例外之一时才调用身份验证函数:

app.use(function (req, res, next) {
  if (req.path === "/index" || req.path === "/login") {
      next();
  } else {
      middleware.authenticate(req, res, next);
  }
});

下面是一个使用Map对象的版本,该对象更容易扩展到更长的路径列表:

var ignorePaths = new Map(["/index", "/login"]);
app.use(function (req, res, next) {
  if (ignorePaths.has(req.path)) {
      next();
  } else {
      middleware.authenticate(req, res, next);
  }
});