gpt4 book ai didi

javascript - 捆绑中间件

转载 作者:行者123 更新时间:2023-12-03 06:19:11 24 4
gpt4 key购买 nike

背景

我正在服务器上使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com