Express 4,将req.path与URL参数匹配

问题描述 投票:1回答:1

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

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

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
  }
}
node.js express express-router
1个回答
2
投票

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

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

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要继续浏览它拥有的所有路由/中间件。

© www.soinside.com 2019 - 2024. All rights reserved.