一元网络论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 124|回复: 0

Cloudflare Worker 反向代理后出现乱码,因为源站使用的是 GBK 编码。如何解决?

[复制链接]

3万

主题

3万

帖子

9万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
96158
发表于 2024-8-31 14:41:32 | 显示全部楼层 |阅读模式
```javascript
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});
const targetUrl = 'https://XXXX.com';
const targetUrlReg = /XXXX\.com/g;
const allowedRegions = ['CN', 'HK'];
const blockedIpAddresses = ['0.0.0.0', '127.0.0.1'];
async function handleRequest(request) {
  const region = request.headers.get('cf-ipcountry').toUpperCase();
  const ipAddress = request.headers.get('cf-connecting-ip');
  const url = new URL(request.url);
  url.hostname = new URL(targetUrl).hostname;
  if (url.protocol === 'http:') {
    url.protocol = 'https:';
    return Response.redirect(url.href);
  }
  let headers = new Headers(request.headers);
  headers.set('Referer', targetUrl);
  headers.set('User-Agent', request.headers.get('user-agent'));
  const params = {
    method: request.method,
    headers,
    body: request.body,
    redirect: 'manual'
  };
  if (blockedIpAddresses.includes(ipAddress)) {
    return new Response('Access denied: Your IP address is blocked by WorkersProxy.', { status: 403 });
  } else if (allowedRegions.includes(region)) {
    let response = await fetch(url, params);
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('text')) {
      let responseBody = await response.text();
      responseBody = await handleResBody(request, responseBody);
      headers = await handleResHeader(response);
      return new Response(responseBody, { status: response.status, statusText: response.statusText, headers });
    } else {
      return response;
    }
  } else {
    return new Response('Access denied: WorkersProxy is not available in your region yet.', { status: 403 });
  }
}
async function handleResBody(request, responseBody) {
  return responseBody.replaceAll(targetUrlReg, new URL(request.url).hostname);
}
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;
}
```
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|一元网络论坛

GMT+8, 2024-11-27 21:33 , Processed in 0.490361 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表