【问题标题】:NodeJs/Express: Authorise all endpoints except oneNodeJs/Express:授权除一个之外的所有端点
【发布时间】:2026-02-06 13:35:01
【问题描述】:

在我的基于 NodeJs/express 的应用程序中,我使用以下中间件授权对所有端点的调用。

 app.use(restrictByCookieMiddleware);

我想授权除一个之外的所有端点,即我不希望“restrictByCookieMiddleware”中间件为“/metrics”端点运行。有没有办法逃脱一个端点?

Here,我找到了一些与应该运行中间件的端点相匹配的示例,我正在寻找一个跳过一个的解决方案。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    你有几个选择:

    首先,您可以在中间件之前定义一个异常路由处理程序。然后,它将处理该路由,并且路由永远不会到达中间件。

    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 对象中。

    然后,创建第二个路由器,其中包含中间件并在其上包含所有其他路由。

    【讨论】:

      【解决方案2】:

      将您要排除的特定路线放在此行之前:

      app.use(restrictByCookieMiddleware);
      

      所以这会解决你的问题。

      【讨论】:

        最近更新 更多