Skip to content

应用 - Hono

¥App - Hono

Hono 是主要对象。它将首先被导入并一直使用到最后。

¥Hono is the primary object. It will be imported first and used until the end.

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

方法

¥Methods

Hono 的一个实例具有以下方法。

¥An instance of Hono has the following methods.

  • 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)

其中前半部分用于路由,请参考 路由部分

¥The first part of them is used for routing, please refer to the routing section.

未找到

¥Not Found

app.notFound 允许你自定义未找到响应。

¥app.notFound allows you to customize a Not Found Response.

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

错误处理

¥Error Handling

app.onError 处理错误并返回自定义响应。

¥app.onError handles an error and returns a customized Response.

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

fire()

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

¥app.fire() automatically adds a global fetch event listener.

这对于遵守 Service Worker API 的环境(例如 非 ES 模块 Cloudflare Workers)很有用。

¥This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.

app.fire() 为你执行以下操作:

¥app.fire() executes the following for you:

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

fetch()

app.fetch 将成为应用的入口点。

¥app.fetch will be entry point of your application.

对于 Cloudflare Workers,你可以使用以下内容:

¥For Cloudflare Workers, you can use the following:

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

或者直接这样做:

¥or just do:

ts
export default 
app

Bun:

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

request()

request 是一种有用的测试方法。

¥request is a useful method for testing.

你可以传递 URL 或路径名来发送 GET 请求。app 将返回 Response 对象。

¥You can pass a URL or pathname to send a GET request. app will return a Response object.

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

你还可以传递 Request 对象:

¥You can also pass a Request object:

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 应用中。

¥The mount() allows you to mount applications built with other frameworks into your Hono application.

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)

严格模式

¥strict mode

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

¥Strict mode defaults to true and distinguishes the following routes.

  • /hello

  • /hello/

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

¥app.get('/hello') will not match GET /hello/.

通过将严格模式设置为 false,两个路径将被平等对待。

¥By setting strict mode to false, both paths will be treated equally.

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

路由选项

¥router option

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

¥The router option specifices which router to use. The default router is SmartRouter. If you want to use RegExpRouter, pass it to a new Hono instance:

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

泛型

¥Generics

你可以传递泛型来指定 c.set/c.get 中使用的 Cloudflare Workers Bindings 和变量的类型。

¥You can pass Generics to specify the types of Cloudflare Workers Bindings and variables used in 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
()
})

Hono v4.7 中文网 - 粤ICP备13048890号