跳转到正文

Mount 中间件 ​

Mount 中间件允许将其他框架构建的应用挂载到 Hono 应用中。

导入 ​

ts
import { 
Hono
} from 'hono'
import {
mount
} from 'hono/mount'

用法 ​

使用 app.all() 将中间件注册到以 /* 结尾的路径上:

ts
import { Router as IttyRouter } from 'itty-router'

// Create itty-router application
const ittyRouter = IttyRouter()

// Handle `GET /itty-router/hello`
ittyRouter.get('/hello', () => new Response('Hello from itty-router'))

const app = new Hono()

app.all('/itty-router/*', mount(ittyRouter.handle))

默认情况下,挂载的应用会接收到新的 Request,其 URL 已移除匹配的路径前缀。访问 /itty-router/hello 的请求会以 /hello 到达 itty-router。

挂载的应用按 handler(request, c.env, c.executionCtx) 调用,参数与 Cloudflare Workers 的 fetch 处理器相同。使用 optionHandler 可以传入不同的参数。

选项 ​

第二个参数可以传入函数或对象。

optional optionHandler: (c: Context) => unknown ​

返回传给挂载应用、位于 Request 之后的参数。数组会展开为多个参数。可以直接将该函数作为第二个参数传入:

ts
// Call `anotherApp(request, c.env)`
app
.
all
(
'/app/*',
mount
(
anotherApp
, (
c
) =>
c
.
env
)
) // Call `anotherApp(request, c.env, c.executionCtx)`
app
.
all
(
'/app/*',
mount
(
anotherApp
, {
optionHandler
: (
c
) => [
c
.
env
,
c
.
executionCtx
],
}) )

optional replaceRequest: ((originalRequest: Request) => Request) | false ​

控制传给挂载应用的 Request:

ts
// `/legacy/users` reaches the mounted application as `/api/users`
app
.
all
(
'/legacy/*',
mount
(
anotherApp
, {
replaceRequest
: (
req
) => {
const
url
= new
URL
(
req
.
url
)
url
.
pathname
=
url
.
pathname
.
replace
(/^\/legacy/, '/api')
return new
Request
(
url
,
req
)
}, }) )

要原样传入原始 Request,可以设为 false,它是 (req) => req 的简写:

ts
app
.
all
(
'/app/*',
mount
(
anotherApp
, {
replaceRequest
: false,
}) )

基于 MIT 许可证发布。