Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Proxy is not working #121

Open
yusukebe opened this issue Jan 7, 2024 · 2 comments
Open

Proxy is not working #121

yusukebe opened this issue Jan 7, 2024 · 2 comments

Comments

@yusukebe
Copy link
Member

yusukebe commented Jan 7, 2024

The following a "proxy pattern" is not working:

import { serve } from '@hono/node-server'
import { Hono } from 'hono'

const app = new Hono()

app.get('/proxy', async (c) => {
  const res = await fetch('https://example.com/')
  const newResponse = new Response(res.body, res)
  return newResponse
})

serve({
  fetch: app.fetch,
  port: 3000
})

Commented honojs/hono#1491 (comment)

@usualoma
Copy link
Member

Although fetch() returns decoded data, the content-encoding and content-length headers remain unchanged in the response, which seems to be causing the problem.

On my environment, the following code returned the correct content.

I have not yet figured out whether this process should be done by each app or by the node-server.

app.get('/proxy', async (c) => {
  const res = await fetch('https://example.com/')
  const headers = { ...res.headers }
  delete headers['content-encoding']
  delete headers['content-length']
  const newResponse = new Response(res.body, { headers })
  return newResponse
})

@zhy0216
Copy link

zhy0216 commented Apr 27, 2024

this works well, modified from https://github.com/linnil1/hono-cf-proxy/blob/main/src/utils_basic.ts

function basicProxy(proxy_url = ""): Handler {
  return async (c) => {
    // remove prefix
    // prefix = /app1/*, path = /app1/a/b
    // => suffix_path = /a/b
    // let path = new URL(c.req.raw.url).pathname
    let path = c.req.path;
    path = path.replace(new RegExp(`^${c.req.routePath.replace("*", "")}`), "/");
    let url = proxy_url ? proxy_url + path : c.req.url;
    // add params to URL
    if (c.req.query()) url = url + "?" + new URLSearchParams(c.req.query());
    // request
    const rep = await fetch(url, {
      method: c.req.method,
      headers: c.req.raw.headers,
      body: c.req.raw.body,
      duplex: "half",
    });
    if (rep.status === 101) return rep;

    return new Response(rep.body, rep);
  };
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants