From beb41a10811c82a29ef95634f23cf5a0c2c5b9aa Mon Sep 17 00:00:00 2001 From: New Bing Date: Mon, 7 Oct 2024 23:49:08 +0800 Subject: [PATCH 1/2] Add reverse proxy example --- examples/proxy.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/examples/proxy.md b/examples/proxy.md index dc5537ea..7655fbb6 100644 --- a/examples/proxy.md +++ b/examples/proxy.md @@ -34,3 +34,21 @@ app.get('/', async (_c) => { The headers of `Response` returned by `fetch` are immutable. So, an error will occur if you modify it. ::: + +## Simple Reverse Proxy + +```ts +import { Hono } from 'hono' + +const app = new Hono() + +app.all('*', async (c) => { + // replace the origin `https://example.com` to the real origin + const res = await fetch('https://example.com', c.req.raw) + // clone the response to return a response with modifiable headers + const newResponse = new Response(res.body, res) + return newResponse +}) + +export default app +``` From 4a2a3d1d7cf3a3cd7df7e85d74dd40633249739e Mon Sep 17 00:00:00 2001 From: New Bing Date: Tue, 8 Oct 2024 20:37:22 +0800 Subject: [PATCH 2/2] fix http redirection of reverse proxy --- examples/proxy.md | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/examples/proxy.md b/examples/proxy.md index 7655fbb6..ff51f25b 100644 --- a/examples/proxy.md +++ b/examples/proxy.md @@ -43,11 +43,26 @@ import { Hono } from 'hono' const app = new Hono() app.all('*', async (c) => { - // replace the origin `https://example.com` to the real origin - const res = await fetch('https://example.com', c.req.raw) - // clone the response to return a response with modifiable headers - const newResponse = new Response(res.body, res) - return newResponse + // replace the origin `https://example.com` to your real upstream + const api = new URL('https://www.example.com') + const url = new URL(c.req.url) + url.protocol = api.protocol + url.host = api.host + url.port = api.port + const upstream = url.toString() + return await fetch(upstream, { + method: c.req.raw.method, + body: c.req.raw.body, + credentials: c.req.raw.credentials, + cache: c.req.raw.cache, + headers: c.req.raw.headers, + referrer: c.req.raw.referrer, + referrerPolicy: c.req.raw.referrerPolicy, + integrity: c.req.raw.integrity, + keepalive: false, + mode: c.req.raw.mode, + redirect: 'manual' + }) }) export default app