admin 发表于 2024-8-31 14:41:32

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

```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;
}
```
页: [1]
查看完整版本: Cloudflare Worker 反向代理后出现乱码,因为源站使用的是 GBK 编码。如何解决?