Appearance
应用 - Hono
🌐 App - Hono
Hono 是主要对象。 它将首先被导入并使用直到结束。
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([路径,]处理函数|中间件...)
- app.all([path,]handler|middleware...)
- app.on(方法|方法数组, 路径|路径数组, 处理函数|中间件...)
- app.use([path,]middleware)
- app.route(path, [app])
- app.基本路径(路径)
- app.未找到(处理程序)
- app.onError(错误, 处理程序)
- app.挂载(路径, 另一个应用)
- app.fire()
- app.fetch(请求, 环境, 事件)
- app.请求(路径, 选项)
它们的第一部分用于路由,请参考路由部分。
🌐 The first part of them is used for routing, please refer to the routing section.
未找到
🌐 Not Found
app.notFound 允许你自定义未找到响应。
ts
app.notFound((c) => {
return c.text('Custom 404 Message', 404)
})WARNING
notFound 方法仅从顶层应用调用。更多信息,请参见此 问题。
错误处理
🌐 Error Handling
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。
🌐 This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
app.fire() 为你执行以下操作:
ts
addEventListener('fetch', (event: FetchEventLike): void => {
event.respondWith(this.dispatch(...))
})fetch()
app.fetch 将是你应用的入口点。
对于 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 appBun:
ts
export default app
export default {
port: 3000,
fetch: app.fetch,
} request()
request 是一种有用的测试方法。
你可以传递一个 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/。
通过将严格模式设置为 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 specifies 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 绑定和变量的类型。
🌐 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()
})