跳转到正文

应用 - 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, [options])
  • app.fire()
  • app.fetch(request, env, event)
  • app.request(path, options)

前面的一些方法用于路由,请参阅路由章节。

未找到资源 ​

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

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

注意

notFound 方法只会在最顶层应用中调用。更多信息请参阅这个 issue。

错误处理 ​

app.onError 可以处理未捕获的错误,并返回自定义响应。

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

说明

如果父应用与其路由都设置了 onError 处理程序,则优先使用路由级别的处理程序。

fire() ​

注意

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() ​

注意

app.mount() 已弃用。请改用 Mount 中间件。

mount() 可以将其他框架构建的应用挂载到 Hono 应用中。

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

// Create itty-router application
const ittyRouter = IttyRouter()

// Handle `GET /itty-router/hello`
ittyRouter.get('/hello', () => new Response('Hello from itty-router'))

// Hono application
const app = new Hono()

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

默认情况下,mount() 会传入一个新的 Request,其 URL 中已移除挂载路径。可以提供 replaceRequest 函数,控制传入被挂载应用的 Request:

ts
app
.
mount
('/app',
handler
, {
replaceRequest
: (
originalRequest
) =>
originalRequest
,
})

要原样传入原始 Request,可以将 replaceRequest 设为 false,作为上述函数的简写:

ts
app
.
mount
('/app',
handler
, {
replaceRequest
: false,
})

严格模式 ​

严格模式默认为 true,会区分以下路由。

  • /hello
  • /hello/

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

将严格模式设为 false 后,这两个路径会被视为相同。

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

路由器选项 ​

router 选项用于指定使用的路由器。默认路由器为 SmartRouter。如果要使用 RegExpRouter,请将其传入新的 Hono 实例:

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

泛型 ​

可以通过泛型指定 Cloudflare Workers Bindings 的类型,以及 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 is `string`
// ...
c
.
set
('user',
user
) // user should be `User`
await
next
()
})

基于 MIT 许可证发布。