應用程式 - 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)
它們的第一部分用於路由,請參考路由章節。
找不到
app.notFound
允許您自訂找不到的回應。
ts
app.notFound((c) => {
return c.text('Custom 404 Message', 404)
})
錯誤處理
app.onError
處理錯誤並返回自訂的回應。
ts
app.onError((err, c) => {
console.error(`${err}`)
return c.text('Custom Error Message', 500)
})
fire()
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'
// 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)
嚴格模式
嚴格模式預設為 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() })
泛型
您可以傳遞泛型來指定 c.set
/c.get
中使用的 Cloudflare Workers Bindings 和變數的類型。
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()
})