跳转到正文

Proxy 辅助工具 ​

Proxy 辅助工具提供将 Hono 应用用作(反向)代理时的实用函数。

导入 ​

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

proxy() ​

proxy() 是用于代理的 fetch() API 包装函数。除代理专用选项外,其参数和返回值与 fetch() 相同。

Accept-Encoding 请求头会替换为当前运行时能够处理的编码。函数移除不必要的响应头,并返回可由处理器发送的 Response 对象。

示例 ​

简单用法:

ts
app.get('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`)
})

复杂用法:

ts
app.get('/proxy/:path', async (c) => {
  const res = await proxy(
    `http://${originServer}/${c.req.param('path')}`,
    {
      headers: {
        ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary.
        'X-Forwarded-For': '127.0.0.1',
        'X-Forwarded-Host': c.req.header('host'),
        Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
      },
    }
  )
  res.headers.delete('Set-Cookie')
  return res
})

也可以将 c.req 作为参数传入。

ts
app.all('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`, {
    ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary.
    headers: {
      ...c.req.header(),
      'X-Forwarded-For': '127.0.0.1',
      'X-Forwarded-Host': c.req.header('host'),
      Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
    },
  })
})

可以通过 customFetch 选项覆盖默认的全局 fetch 函数:

ts
app.get('/proxy', (c) => {
  return proxy('https://example.com/', {
    customFetch,
  })
})

Connection 请求头处理 ​

默认情况下,proxy() 忽略 Connection 请求头,以防止逐跳请求头注入攻击。可以通过 strictConnectionProcessing 选项启用严格遵循 RFC 9110 的处理:

ts
// Default behavior (recommended for untrusted clients)
app.get('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`, c.req)
})

// Strict RFC 9110 compliance (use only in trusted environments)
app.get('/internal-proxy/:path', (c) => {
  return proxy(`http://${internalServer}/${c.req.param('path')}`, {
    ...c.req,
    strictConnectionProcessing: true,
  })
})

ProxyFetch ​

proxy() 的类型定义为 ProxyFetch,如下所示:

ts
interface ProxyRequestInit extends Omit<RequestInit, 'headers'> {
  raw?: Request
  customFetch?: (request: Request) => Promise<Response>
  strictConnectionProcessing?: boolean
  headers?:
    | HeadersInit
    | [string, string][]
    | Record<RequestHeader, string | undefined>
    | Record<string, string | undefined>
}

interface ProxyFetch {
  (
    input: string | URL | Request,
    init?: ProxyRequestInit
  ): Promise<Response>
}

基于 MIT 许可证发布。