App - Hono

Hono 是主要的对象。它会被首先导入并使用到最后。

  1. import { Hono } from 'hono'
  2. const app = new Hono()
  3. //...
  4. export default app // 用于 Cloudflare Workers 或 Bun

方法 (Methods)

一个 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)

前半部分方法用于路由,请参考 routing 部分

Not Found

app.notFound 允许你自定义 Not Found 响应。

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

错误处理 (Error Handling)

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

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

fire()

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

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

这对于遵循 Service Worker API 的环境非常有用,比如 非 ES module 的 Cloudflare Workers

app.fire() 实际上执行的是:

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

fetch()

app.fetch 是你应用的入口点。

对于 Cloudflare Workers,你可以这样使用:

  1. export default {
  2. fetch(request: Request, env: Env, ctx: ExecutionContext) {
  3. return app.fetch(request, env, ctx)
  4. },
  5. }

或者直接这样写:

  1. export default app

在 Bun 中:

  1. export default app
  2. export default {
  3. port: 3000,
  4. fetch: app.fetch,
  5. }

request()

request 是一个用于测试的实用方法。

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

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

你也可以传入一个 Request 对象:

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

mount()

mount() 允许你将其他框架构建的应用挂载到你的 Hono 应用中。

  1. import { Router as IttyRouter } from 'itty-router'
  2. import { Hono } from 'hono'
  3. // 创建 itty-router 应用
  4. const ittyRouter = IttyRouter()
  5. // 处理 `GET /itty-router/hello`
  6. ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
  7. // Hono 应用
  8. const app = new Hono()
  9. // 挂载!
  10. app.mount('/itty-router', ittyRouter.handle)

strict 模式

strict 模式默认值为 true,会区分如下路由:

  • /hello
  • /hello/

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

通过设置 strict 为 false,两者将被视为相同路径:

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

router 选项

router 选项指定使用哪个路由器。默认使用 SmartRouter。如果你想使用 RegExpRouter,可以这样传入:

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

泛型 (Generics)

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

  1. type Bindings = {
  2. TOKEN: string
  3. }
  4. type Variables = {
  5. user: User
  6. }
  7. const app = new Hono<{
  8. Bindings: Bindings
  9. Variables: Variables
  10. }>()
  11. app.use('/auth/*', async (c, next) => {
  12. const token = c.env.TOKEN // token 是 `string`
  13. // ...
  14. c.set('user', user) // user 是 `User`
  15. await next()
  16. })