返回
创建于
状态公开
在 Hono 中使用如下写法:
1app.use(auth).get('/sync/telegram/:channel_name', handler)实际上等价于:
- 对 所有后续路由 应用
auth中间件(除非你特意改变路由结构)。 - 所有通过
app.get()等定义的路由,都会先经过auth处理。
✅ 正确使用方式:中间件作用范围限制
你应该将中间件限定在某个子路由路径上,而不是直接全局调用 app.use(auth)。以下是几种推荐方式:
✅ 方式一:使用子应用(推荐)
1import { Hono } from 'hono'
2
3const app = new Hono()
4
5// 创建子应用
6const protectedRoutes = new Hono()
7
8// 给子应用添加中间件
9protectedRoutes.use(auth)
10
11// 添加需要保护的路由
12protectedRoutes.get('/sync/telegram/:channel_name', handler1)
13protectedRoutes.get('/sync/telegram/test', handler2)
14
15// 挂载子应用
16app.route('/sync', protectedRoutes)
17
18// 其他不需要 auth 的路由
19app.get('/internal/sync/telegram/:channel_name', handler3)这样,只有 /sync/... 路由使用了 auth 中间件,/internal/sync/... 不受影响。
✅ 方式二:精确路径使用中间件(不推荐维护复杂路由时)
1app.get('/sync/telegram/:channel_name', auth, handler)
2app.get('/sync/telegram/test', auth, handler2)
3app.get('/internal/sync/telegram/:channel_name', handler3) // 不加 auth虽然写法简单,但如果你有很多需要 auth 的路由,这个方式就会变得不易维护,容易漏加。
🧠 补充:为什么 app.use(auth).get(...) 会影响后续?
Hono 中的 .use() 是链式调用的 API,它会将中间件“挂在当前路由上下文”上。如果你这样写:
1app.use(auth) // 这会注册一个全局的 auth 中间件
2app.get('/route1', handler1)
3app.get('/route2', handler2)就相当于:
1app.use('*', auth)这会导致 auth 应用到所有路径。
✅ 最佳实践总结
| 用法 | 是否推荐 | 说明 |
|---|---|---|
app.use(auth) | ❌ 不推荐 | 全局中间件,除非你真的想所有路由都验证 |
app.get('/path', auth, handler) | ✅ 推荐 | 小项目或单个路由 |
子应用 + .route() | ✅✅ 强烈推荐 | 项目大时组织清晰、易维护 |