vps交流

cf worker反代后乱码,原来是源站是gbk编码,有办法解决吗?


如题,原来的worker代码是抄的网上的

addEventListener(‘fetch’, event => {
  event.respondWith(handleRequest(event.request));
});

// 准备反代的目的域名,域名自己更改为想要的
let target_url = "https://XXXX.com";
// 要替换内容的正则表达式
let target_url_reg = /XXXX.com/g;

// 你希望运行哪些国家访问
const allowed_region = [‘CN’, ‘HK’]

// 禁止自访问
const blocked_ip_address = [‘0.0.0.0’, ‘127.0.0.1’]

async function handleRequest(request) {
  const region = request.headers.get(‘cf-ipcountry’).toUpperCase();
  const ip_address = request.headers.get(‘cf-connecting-ip’);
  let url = new URL(request.url);
  url.hostname = new URL(target_url).hostname;

  if (url.protocol == ‘http:’) {
    url.protocol = ‘https:’
    response = Response.redirect(url.href);
    return response;
}

  // 复制请求对象并更新它的属性
  let headers = new Headers(request.headers);
  headers.set("Referer", target_url);
  headers.set("User-Agent", request.headers.get("user-agent"));

  const param = {
    method: request.method,
    headers: headers,
    body: request.body,
    redirect: "manual"
  }

    if (blocked_ip_address.includes(ip_address)) {
        response = new Response(‘Access denied: Your IP address is blocked by WorkersProxy.’, {
            status: 403
        });
    } else if(allowed_region.includes(region)){
  let response = await fetch(url, param);

  // 检查响应头中的内容类型
  const contentType = response.headers.get(‘content-type’);
  if (contentType && contentType.includes(‘text’)) {

    // 如果是文本类型,替换响应主体中的URL
    let responseBody = await response.text();
    responseBody = await handleResBody(request,responseBody);

    // 复制响应对象并更新它的属性
    let headers = await handleResHeader(response);

    return new Response(responseBody, {
      status: response.status,
      statusText: response.statusText,
      headers: headers
    });
  } else {
    // 如果不是文本类型,直接返回响应对象
    return response;
  }
    } else{
        response = new Response(‘Access denied: WorkersProxy is not available in your region yet.’, {
            status: 403
        });
  }
}

async function handleResBody(request, responseBody){
  responseBody = responseBody.replaceAll(target_url_reg, new URL(request.url).hostname);
  return responseBody;
}

async function handleResHeader(resp){
  let headers = new Headers(resp.headers);
  headers.set(‘Access-Control-Allow-Origin’, ‘*’);
  headers.set(‘Access-Control-Allow-Methods’, ‘GET’);
  headers.set(‘Access-Control-Allow-Headers’, ‘Content-Type’);
  return headers;
}

遇事不决先问AI
丢给AI写就行了,这样的小问题还不简单
AI好像没搞定cf worker反代后乱码,原来是源站是gbk编码,有办法解决吗?
自己顶一下,ai改了几次也是错的,在后面就没有免费次数了cf worker反代后乱码,原来是源站是gbk编码,有办法解决吗?
  1. https://gist.github.com/BlueSkyXN/63459597f05567083afdca6d1abbcd1a

复制代码

查CFworker的文档