你有几个选择:
首先,您可以在中间件之前定义一个异常路由处理程序。然后,它将处理该路由,并且路由永远不会到达中间件。
app.get("/login", (req, res) => {
// handle that one special route here
});
// all other routes will get this middleware
app.use(restrictByCookieMiddleware);
其次,您可以为中间件制作一个包装器,与一个特定的路由进行比较,如果是该路由则跳过中间件:
app.use((req, res, next) => {
// shortcircuit the /login path so it doesn't call the middleware
if (req.path === "/login") {
next();
} else {
restrictByCookieMiddleware(req, res, next);
}
});
// then, somewhere else in your code would be the /login route
app.get("/login", ...);
第三,如果您有多个路由要跳过中间件,您可以按路由分段。为非中间件路由创建一个路由器,并将它们全部放在该路由器上。首先将该路由器挂接到app 对象中。
然后,创建第二个路由器,其中包含中间件并在其上包含所有其他路由。