表达 4,匹配 req.path 与 URL 参数

Express 4, matching req.path with URL param

我为 Express 路由器制作了一个自定义中间件,允许我将 API 的某些端点列入白名单以排除身份验证。但是,我有一条依赖于 URL 参数的路由,我无法让我的中间件按预期工作。显然 :profileId 什么也没做,我的 API 端点仍然需要身份验证。

我需要将该路径从身份验证中排除的原因是因为我的 React 前端应该向 public 显示该数据(没有人注册和登录)。任何提示如何解决这个问题?

const apiAuth = (req, res, next) => {
  let authRequired = true;

  if (
    req.path == "/api/users/register" ||
    req.path == "/api/users/login" ||
    req.path == "/api/profiles/:profileId"
  ) {
    authRequired = false;
  }

  if (authRequired == true) {
    // Auth check logic
  }
}

有一些更好的方法来处理中间件的要求,通常用于您建议的方法:

仅在您需要的路由中包含您的身份验证中间件:

const authenticationMiddleware = (req, res, next) => {
    // your login check logic
}

router.get('/api/users/me', authenticationMiddleware, (req, res, next) => {
    // your route logic, this endpoint now requires you to be logged in, as you have specified your authentication middleware in the declaration,
})

router.get('/api/profiles/:profileId', (req, res, next) => {
     // your route logic, this endpoint does not require you to be logged in as you have not put the middleware in the route delcaration
})

或者,根据调用路由的位置添加身份验证中间件:

router.get('/api/profiles/:profileId', (req, res, next) => {
    // your route logic, this endpoint does not require you to be logged as we have not told our router to use the middleware yet
})

router.use(authenticationMiddleware)

router.get('/api/users/me', (req, res, next) => {
    // your route logic, this endpoint now requires you to be logged in, as the router has been told to use the middleware at this point.
})

为什么使用这些方法?尝试将您正在进行的所有 routerapp 调用想象成添加到一个堆栈,该堆栈用于处理对您的站点或 API 的调用。当它通过寻找路由的方式工作时,它将调用它发现的任何中间件。

这解决了必须声明需要或不需要特定身份验证等的路由列表或数组的问题。

如果你想让它工作,你还需要确保在你的中间件中调用 next(),因为这告诉 express 继续遍历它拥有的所有 routes/middleware。