对除特定路径之外的所有路径使用 Express 中的特定中间件 [英] Use specific middleware in Express for all paths except a specific one
问题描述
我在 node.js 中使用 Express 框架和一些中间件功能:
I am using the Express framework in node.js with some middleware functions:
var app = express.createServer(options);
app.use(User.checkUser);
我可以使用带有附加参数的 .use
函数来仅在特定路径上使用此中间件:
I can use the .use
function with an additional parameter to use this middleware only on specific paths:
app.use('/userdata', User.checkUser);
是否可以使用路径变量,以便将中间件用于除特定路径(即根路径)之外的所有路径?
Is it possible to use the path variable so that the middleware is used for all paths except a specific one, i.e. the root path?
我正在考虑这样的事情:
I am thinking about something like this:
app.use('!/', User.checkUser);
所以 User.checkUser
总是被调用,除了根路径.
So User.checkUser
is always called except for the root path.
推荐答案
我会将 checkUser 中间件添加到我的所有路径中,除了主页.
I would add checkUser middleware to all my paths, except homepage.
app.get('/', routes.index);
app.get('/account', checkUser, routes.account);
或
app.all('*', checkUser);
function checkUser(req, res, next) {
if ( req.path == '/') return next();
//authenticate user
next();
}
您可以扩展它以在未经身份验证的路径数组中搜索 req.path:
You could extend this to search for the req.path in an array of non-authenticated paths:
function checkUser(req, res, next) {
const nonSecurePaths = ['/', '/about', '/contact'];
if (nonSecurePaths.includes(req.path)) return next();
//authenticate user
next();
}
这篇关于对除特定路径之外的所有路径使用 Express 中的特定中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!