本帖最后由 WwzwW 于 2023-5-24 12:20 编辑
15行那个可以不需要填写自己的反代地址,用这个就行:
- new URL(request.url).hostname
复制代码
甚至可以更通用的反代,完整代码:
- addEventListener('fetch', event => {
- event.respondWith(handleRequest(event.request));
- });
- // 准备反代的目的域名
- let target_url = "hostloc.wiki";
- async function handleRequest(request) {
- let url = new URL(request.url);
- url.hostname = target_url;
- let response = await fetch(url, {
- method: request.method,
- headers: request.headers,
- body: request.body
- });
- // 检查响应头中的内容类型
- const contentType = response.headers.get('content-type');
- if (contentType && contentType.includes('text')) {
- // 如果是文本类型,替换响应主体中的URL
- let responseBody = await response.text();
-
- responseBody = responseBody.replace(/hostloc\.com/g, new URL(request.url).hostname);
- // 复制响应对象并更新它的属性
- let headers = new Headers(response.headers);
- headers.set('Access-Control-Allow-Origin', '*');
- headers.set('Access-Control-Allow-Methods', 'GET');
- headers.set('Access-Control-Allow-Headers', 'Content-Type');
- return new Response(responseBody, {
- status: response.status,
- statusText: response.statusText,
- headers: headers
- });
- } else {
- // 如果不是文本类型,直接返回响应对象
- return response;
- }
- }
复制代码
|