我正在使用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');
}
});
}
}
任何建议都会非常感谢...提前致谢!
答案 0 :(得分:1)
您可以插入一个查看路径的垫片,如果路径不是您的例外,则只调用authenticate函数:
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);
}
});