代码如下:
const TELEGRAPH_URL = 'https://subdomain.domain.com'; addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url); url.host = TELEGRAPH_URL.replace(/^https?:\/\//, ''); const modifiedRequest = new Request(url.toString(), { headers: request.headers, method: request.method, body: request.body, redirect: 'manual' // 设置为 'manual' 以拦截重定向 }); const response = await fetch(modifiedRequest); let modifiedResponse; if (response.status >= 300 && response.status < 400) { // 如果是重定向响应,创建一个新的Response对象并保留重定向的头信息 modifiedResponse = new Response(null, response); } else { // 对于非重定向响应,正常传递响应体和头信息 modifiedResponse = new Response(response.body, response); } // 添加允许跨域访问的响应头 modifiedResponse.headers.set('Access-Control-Allow-Origin', '*'); return modifiedResponse; }