Context
为了处理 Request 和 Response,你可以使用 Context 对象。
req
req 是 HonoRequest 的实例。更多详情,请查看 HonoRequest。
app.get('/hello', (c) => {
const userAgent = c.req.header('User-Agent')
// ...
})body()
返回 HTTP 响应。
你可以使用 c.header() 设置 headers,使用 c.status 设置 HTTP 状态码。 这些也可以在 c.text()、c.json() 等方法中设置。
INFO
Note: 当返回 Text 或 HTML 时,推荐使用 c.text() 或 c.html()。
app.get('/welcome', (c) => {
// 设置 headers
c.header('X-Message', 'Hello!')
c.header('Content-Type', 'text/plain')
// 设置 HTTP 状态码
c.status(201)
// 返回响应 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',
})
})Response 与下面代码相同。
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()
渲染 JSON,Content-Type 为 application/json。
app.get('/api', (c) => {
return c.json({ message: 'Hello!' })
})html()
渲染 HTML,Content-Type 为 text/html。
app.get('/', (c) => {
return c.html('<h1>Hello! Hono!</h1>')
})notFound()
返回 Not Found Response。
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 对象
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() 设置布局(layout)。
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 对象
app.get('/foo', async (c) => {
c.executionCtx.waitUntil(c.env.KV.put(key, data))
// ...
})event
// 用于类型推断的类型定义
type Bindings = {
MY_KV: KVNamespace
}
const app = new Hono<{ Bindings: Bindings }>()
// FetchEvent 对象 (仅在使用 Service Worker 语法时设置)
app.get('/foo', async (c) => {
c.event.waitUntil(c.env.MY_KV.put(key, data))
// ...
})env
在 Cloudflare Workers 中,绑定到 worker 的环境变量、secrets、KV 命名空间、D1 数据库、R2 bucket 等被称为 bindings。 无论类型如何,bindings 始终作为全局变量可用,并且可以通过 context c.env.BINDING_KEY 访问。
// 用于类型推断的类型定义
type Bindings = {
MY_KV: KVNamespace
}
const app = new Hono<{ Bindings: Bindings }>()
// Cloudflare Workers 的 Environment 对象
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) {
// 执行某些操作...
}
})ContextVariableMap
例如,如果你希望在使用特定中间件时向变量添加类型定义,你可以扩展 ContextVariableMap。例如:
declare module 'hono' {
interface ContextVariableMap {
result: string
}
}然后你可以在你的中间件中使用它:
const mw = createMiddleware(async (c, next) => {
c.set('result', 'some values') // result 是 string 类型
await next()
})在处理程序中,变量被推断为正确的类型:
app.get('/', (c) => {
const val = c.get('result') // val 是 string 类型
// ...
return c.json({ result: val })
})