即使 expressjs 中没有内置的中间件过滤系统,您至少可以通过两种方式实现这一点。
第一种方法是挂载所有要跳转到正则表达式路径的中间件,而不是包含否定查找:
// Skip all middleware except rateLimiter and proxy when route is /example_route
app.use(/\/((?!example_route).)*/, app_lookup);
app.use(/\/((?!example_route).)*/, timestamp_validator);
app.use(/\/((?!example_route).)*/, request_body);
app.use(/\/((?!example_route).)*/, checksum_validator);
app.use(rateLimiter);
app.use(/\/((?!example_route).)*/, whitelist);
app.use(proxy);
第二种方法,可能更易读和更简洁,是用一个小的辅助函数包装你的中间件:
var unless = function(path, middleware) {
return function(req, res, next) {
if (path === req.path) {
return next();
} else {
return middleware(req, res, next);
}
};
};
app.use(unless('/example_route', app_lookup));
app.use(unless('/example_route', timestamp_validator));
app.use(unless('/example_route', request_body));
app.use(unless('/example_route', checksum_validator));
app.use(rateLimiter);
app.use(unless('/example_route', whitelist));
app.use(proxy);
如果您需要比简单的path === req.path 更强大的路由匹配,您可以使用 Express 内部使用的path-to-regexp module。
更新:- 在express 4.17 req.path 中只返回'/',所以使用req.baseUrl:
var unless = function(path, middleware) {
return function(req, res, next) {
if (path === req.baseUrl) {
return next();
} else {
return middleware(req, res, next);
}
};
};