Skip to content

WIP:Add reverse proxy example#510

Open
iflamed wants to merge 2 commits intohonojs:mainfrom
iflamed:patch-1
Open

WIP:Add reverse proxy example#510
iflamed wants to merge 2 commits intohonojs:mainfrom
iflamed:patch-1

Conversation

@iflamed
Copy link

@iflamed iflamed commented Oct 7, 2024

Simple to use!

import { Hono } from 'hono'

const app = new Hono()

app.all('*', async (c) => {
  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

@iflamed iflamed changed the title Add reverse proxy example WIP:Add reverse proxy example Oct 10, 2024
@yusukebe
Copy link
Member

Hi @iflamed

Try this:

app.all('*', (c) => {
  const url = new URL(c.req.path, 'https://www.example.com')
  return fetch(url, c.req.raw)
})

@iflamed
Copy link
Author

iflamed commented Oct 11, 2024

@yusukebe I have tried this, it will follow the redirect, and the url will lose the query string.

I will update my code later, it not support Cloudflare worker.

@yusukebe
Copy link
Member

@iflamed

I haven't tried it yet, but I think here:

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'
})

can be written like this:

return await fetch(upstream, {
  ...c.req.raw,
  keepalive: false,
  redirect: 'manual'
})

@iflamed
Copy link
Author

iflamed commented Oct 11, 2024

@yusukebe yes, some attributes not supported by Cloudflare pages.

@yusukebe
Copy link
Member

@iflamed

Ah. We have to remove some properties from c.req.raw, right?

@iflamed
Copy link
Author

iflamed commented Oct 11, 2024

@yusukebe yes, and I found my code not support post request, will report content-length not match.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants