Skip to content

代理

¥Proxy

提示

更新:我们引入了新的代理助手,以简化代理功能。查看 Proxy Helper 文档 以了解更多详情。

¥Update: We've introduced the new Proxy Helper for easier proxy functionality. Check out the Proxy Helper documentation for more details.

ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/posts/:filename{.+.png$}', (c) => {
  const referer = c.req.header('Referer')
  if (referer && !/^https:\/\/example.com/.test(referer)) {
    return c.text('Forbidden', 403)
  }
  return fetch(c.req.url)
})

app.get('*', (c) => {
  return fetch(c.req.url)
})

export default app

提示

如果你使用类似的代码看到 Can't modify immutable headers. 错误,则需要克隆响应对象。

¥If you can see Can't modify immutable headers. error with a similar code, you need to clone the response object.

ts
app.get('/', async (_c) => {
  const response = await fetch('https://example.com')
  // clone the response to return a response with modifiable headers
  const newResponse = new Response(response.body, response)
  return newResponse
})

fetch 返回的 Response 的标头是不可变的。如果你修改它,将会发生错误。

¥The headers of Response returned by fetch are immutable. So, an error will occur if you modify it.

Hono v4.11 中文网 - 粤ICP备13048890号