将钩子应用到某些路由 Node.js
Apply hook to certain routes Node.js
我正在使用 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);
}
});
我正在使用 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);
}
});