Skip to content

应用 - Hono

Hono 是核心对象。 它会在一开始被导入,并贯穿整个应用程序。

ts
import { 
Hono
} from 'hono'
const
app
= new
Hono
()
//... export default
app
// for Cloudflare Workers or Bun

方法

Hono 实例提供以下方法:

  • app.HTTP_METHOD([path,]handler|middleware...)
  • app.all([path,]handler|middleware...)
  • app.on(method|method[], path|path[], handler|middleware...)
  • app.use([path,]middleware)
  • app.route(path, [app])
  • app.basePath(path)
  • app.notFound(handler)
  • app.onError(err, handler)
  • app.mount(path, anotherApp)
  • app.fire()
  • app.fetch(request, env, event)
  • app.request(path, options)

其中前面几项用于定义路由,详见路由章节

未找到(Not Found)

app.notFound 可以自定义未找到时返回的响应。

ts
app
.
notFound
((
c
) => {
return
c
.
text
('Custom 404 Message', 404)
})

WARNING

notFound 仅会由顶层应用触发。详情请参阅此问题

错误处理

app.onError 能捕获未处理的异常并返回自定义响应。

ts
app
.
onError
((
err
,
c
) => {
console
.
error
(`${
err
}`)
return
c
.
text
('Custom Error Message', 500)
})

INFO

当父应用和路由同时注册了 onError 处理器时,会优先使用路由级处理器。

fire()

WARNING

app.fire() 已被弃用。请改用 hono/service-worker 中的 fire()。详情参见Service Worker 文档

app.fire() 会自动添加全局的 fetch 事件监听器。

对于遵循 Service Worker API 的运行环境(例如非 ES 模块的 Cloudflare Workers)来说这会很有用。

app.fire() 会为你执行以下代码:

ts
addEventListener('fetch', (event: FetchEventLike): void => {
  event.respondWith(this.dispatch(...))
})

fetch()

app.fetch 是应用程序的入口。

在 Cloudflare Workers 中可以这样使用:

ts
export default {
  
fetch
(
request
: Request,
env
:
Env
,
ctx
:
ExecutionContext
) {
return
app
.
fetch
(
request
,
env
,
ctx
)
}, }

或者直接:

ts
export default 
app

Bun:

ts
export default app 
export default {  
  port: 3000, 
  fetch: app.fetch, 
} 

request()

request 方法非常适合用于测试。

你可以传入 URL 或路径来发送 GET 请求,app 会返回一个 Response 对象。

ts
test
('GET /hello is ok', async () => {
const
res
= await
app
.
request
('/hello')
expect
(
res
.
status
).toBe(200)
})

你也可以传入 Request 对象:

ts
test
('POST /message is ok', async () => {
const
req
= new
Request
('Hello!', {
method
: 'POST',
}) const
res
= await
app
.
request
(
req
)
expect
(
res
.
status
).toBe(201)
})

mount()

mount() 让你可以在 Hono 应用中挂载其他框架构建的应用。

ts
import { Router as IttyRouter } from 'itty-router'
import { Hono } from 'hono'

// 创建 itty-router 应用
const ittyRouter = IttyRouter()

// 处理 `GET /itty-router/hello`
ittyRouter.get('/hello', () => new Response('来自 itty-router 的问候'))

// Hono 应用
const app = new Hono()

// 挂载!
app.mount('/itty-router', ittyRouter.handle)

strict 模式

严格模式默认开启(值为 true),会将以下路由视为不同路径:

  • /hello
  • /hello/

app.get('/hello') 不会匹配 GET /hello/

如果将 strict mode 设为 false,上述两个路径将被视为同一路由。

ts
const 
app
= new
Hono
({
strict
: false })

router 选项

router 选项用于指定路由器。默认值是 SmartRouter。如果想使用 RegExpRouter,可以在创建 Hono 实例时传入:

ts
import { 
RegExpRouter
} from 'hono/router/reg-exp-router'
const
app
= new
Hono
({
router
: new
RegExpRouter
() })

泛型

可以通过泛型参数声明 Cloudflare Workers 的 Binding 类型,以及 c.set/c.get 中使用的变量类型。

ts
type 
Bindings
= {
TOKEN
: string
} type
Variables
= {
user
:
User
} const
app
= new
Hono
<{
Bindings
:
Bindings
Variables
:
Variables
}>()
app
.
use
('/auth/*', async (
c
,
next
) => {
const
token
=
c
.
env
.
TOKEN
// token 的类型是 `string`
// ...
c
.
set
('user',
user
) // user 应当是 `User`
await
next
()
})

Released under the MIT License.