javascript - 捆绑中间件

标签 javascript node.js express routes express-4

背景

我正在服务器上使用 Node/Express 4 编写一个 Web 应用程序。

我的一些路由需要向公众开放,但其他路由需要使用 token 身份验证来保护。执行 token 认证的过程本质上分为以下 4 个中间件:

router.post('/api/my-secure-endpoint',
  check_token_integrity,
  check_token_expiry,
  check_route_permissions(['perm1', 'perm2',...]),
  refresh_token_if_necessary,
  ...
);

check_route_permissions 实际上是一个函数,它为所提供的路由权限返回自定义的中间件函数,但在其他方面没有任何特殊之处。

问题/问题

我觉得一直把这些写出来是相当湿的。有没有办法创建 bundle ,例如authenticate 本质上只是这些中间件的占位符?

这种情况的常见模式是什么?

可能的解决方案

我可以创建一个函数,返回一个数组,其元素是中间件函数,然后自己将其展平,例如

function auth(perms) {    
  return [
    check_token_integrity,
    check_token_expiry,
    check_route_permissions(perms),
    refresh_token_if_necessary,
  ];
}

router.post.apply(this,
  _.concat('/api/my-secure-endpoint', auth(['perm1', 'perm2']), [my, other, middlewares]));
);

但是,我想知道是否有更干净或更标准化的方法来执行此操作。

最佳答案

Express 支持中间件数组,所以这可以工作:

router.post('/api/my-secure-endpoint',
  auth(['perm1', 'perm2']),
  [your, other, middlewares],
  ...
)

更多信息here .

关于javascript - 捆绑中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945359/

相关文章:

javascript - 代码审查 - if else 函数

javascript - 使用原型(prototype)链的问题

json - package.json 必须是实际的 JSON,而不仅仅是 JavaScript

javascript - 我的函数和重定向到路线之间的延迟

javascript - JQuery 翻译功能在 firefox/chrome 中不起作用

javascript - RegEx如何正确使用来校验str

node.js - 如何为 sequelize 多对多关联方法创建类型安全,例如(setModels 等)

javascript - Mozilla PDF.js 字体问题

node.js - 在express.js Controller 中await 是否会影响性能?

javascript - 从数组中返回与键 :value pair of an object nested in the object I need to return 匹配的对象