Context
您可以使用 Context
物件來處理請求和回應。
req
req
是 HonoRequest 的實例。
app.get('/hello', (c) => {
const userAgent = c.req.header('User-Agent')
// ...
})
body()
回傳 HTTP 回應。
您可以使用 c.header()
設定標頭,並使用 c.status
設定 HTTP 狀態碼。這也可以在 c.text()
、c.json()
等等中設定。
資訊
注意:當回傳文字或 HTML 時,建議使用 c.text()
或 c.html()
。
app.get('/welcome', (c) => {
// Set headers
c.header('X-Message', 'Hello!')
c.header('Content-Type', 'text/plain')
// Set HTTP status code
c.status(201)
// Return the response body
return c.body('Thank you for coming')
})
您也可以寫成如下。
app.get('/welcome', (c) => {
return c.body('Thank you for coming', 201, {
'X-Message': 'Hello!',
'Content-Type': 'text/plain',
})
})
回應與以下相同。
new Response('Thank you for coming', {
status: 201,
headers: {
'X-Message': 'Hello!',
'Content-Type': 'text/plain',
},
})
text()
以 Content-Type:text/plain
渲染文字。
app.get('/say', (c) => {
return c.text('Hello!')
})
json()
以 Content-Type:application/json
渲染 JSON。
app.get('/api', (c) => {
return c.json({ message: 'Hello!' })
})
html()
以 Content-Type:text/html
渲染 HTML。
app.get('/', (c) => {
return c.html('<h1>Hello! Hono!</h1>')
})
notFound()
回傳 找不到
的回應。
app.get('/notfound', (c) => {
return c.notFound()
})
redirect()
重定向,預設狀態碼為 302
。
app.get('/redirect', (c) => {
return c.redirect('/')
})
app.get('/redirect-permanently', (c) => {
return c.redirect('/', 301)
})
res
// Response object
app.use('/', async (c, next) => {
await next()
c.res.headers.append('X-Debug', 'Debug message')
})
set() / get()
取得和設定任意鍵值對,其生命週期為當前請求。這允許在中介軟體之間或從中介軟體到路由處理程式之間傳遞特定值。
app.use(async (c, next) => {
c.set('message', 'Hono is cool!!')
await next()
})
app.get('/', (c) => {
const message = c.get('message')
return c.text(`The message is "${message}"`)
})
將 Variables
作為泛型傳遞給 Hono
的建構子,以使其類型安全。
type Variables = {
message: string
}
const app = new Hono<{ Variables: Variables }>()
c.set
/ c.get
的值僅保留在同一個請求中。它們不能在不同的請求之間共享或持久化。
var
您也可以使用 c.var
存取變數的值。
const result = c.var.client.oneMethod()
如果您想建立提供自訂方法的中介軟體,請像這樣寫
type Env = {
Variables: {
echo: (str: string) => string
}
}
const app = new Hono()
const echoMiddleware = createMiddleware<Env>(async (c, next) => {
c.set('echo', (str) => str)
await next()
})
app.get('/echo', echoMiddleware, (c) => {
return c.text(c.var.echo('Hello!'))
})
如果您想在多個處理程式中使用中介軟體,您可以使用 app.use()
。然後,您必須將 Env
作為泛型傳遞給 Hono
的建構子,以使其類型安全。
const app = new Hono<Env>()
app.use(echoMiddleware)
app.get('/echo', (c) => {
return c.text(c.var.echo('Hello!'))
})
render() / setRenderer()
您可以在自訂中介軟體中使用 c.setRenderer()
設定佈局。
app.use(async (c, next) => {
c.setRenderer((content) => {
return c.html(
<html>
<body>
<p>{content}</p>
</body>
</html>
)
})
await next()
})
然後,您可以使用 c.render()
在此佈局中建立回應。
app.get('/', (c) => {
return c.render('Hello!')
})
輸出結果將會是
<html>
<body>
<p>Hello!</p>
</body>
</html>
此外,此功能提供了自訂引數的彈性。為了確保類型安全,可以將類型定義為
declare module 'hono' {
interface ContextRenderer {
(
content: string | Promise<string>,
head: { title: string }
): Response | Promise<Response>
}
}
以下是如何使用此功能的範例
app.use('/pages/*', async (c, next) => {
c.setRenderer((content, head) => {
return c.html(
<html>
<head>
<title>{head.title}</title>
</head>
<body>
<header>{head.title}</header>
<p>{content}</p>
</body>
</html>
)
})
await next()
})
app.get('/pages/my-favorite', (c) => {
return c.render(<p>Ramen and Sushi</p>, {
title: 'My favorite',
})
})
app.get('/pages/my-hobbies', (c) => {
return c.render(<p>Watching baseball</p>, {
title: 'My hobbies',
})
})
executionCtx
// ExecutionContext object
app.get('/foo', async (c) => {
c.executionCtx.waitUntil(c.env.KV.put(key, data))
// ...
})
event
// Type definition to make type inference
type Bindings = {
MY_KV: KVNamespace
}
const app = new Hono<{ Bindings: Bindings }>()
// FetchEvent object (only set when using Service Worker syntax)
app.get('/foo', async (c) => {
c.event.waitUntil(c.env.MY_KV.put(key, data))
// ...
})
env
在 Cloudflare Workers 環境變數中,綁定到 worker 的密鑰、KV 命名空間、D1 資料庫、R2 bucket 等都稱為綁定。無論類型如何,綁定始終以全域變數的形式提供,並且可以透過 context c.env.BINDING_KEY
存取。
// Type definition to make type inference
type Bindings = {
MY_KV: KVNamespace
}
const app = new Hono<{ Bindings: Bindings }>()
// Environment object for Cloudflare Workers
app.get('/', async (c) => {
c.env.MY_KV.get('my-key')
// ...
})
error
如果 Handler 拋出錯誤,則錯誤物件會放置在 c.error
中。您可以在中介軟體中存取它。
app.use(async (c, next) => {
await next()
if (c.error) {
// do something...
}
})
ContextVariableMap
例如,如果您希望在使用了特定中介軟體時向變數添加類型定義,您可以擴展 ContextVariableMap
。例如
declare module 'hono' {
interface ContextVariableMap {
result: string
}
}
然後,您可以在您的中介軟體中使用它
const mw = createMiddleware(async (c, next) => {
c.set('result', 'some values') // result is a string
await next()
})
在處理程式中,變數會被推斷為適當的類型
app.get('/', (c) => {
const val = c.get('result') // val is a string
// ...
return c.json({ result: val })
})