如何在 cloudflare workers 中设置 CORS header?

How to set CORS header in cloudflare workers?

我正在使用 cloudflare worker 创建反向代理,但我无法将其嵌入主域,因为它会出现 CORS 错误:

Access to image at 'https://example.workers.dev/96384873_p0.png' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是 workers 中的代码

addEventListener("fetch", event => {
  let url = new URL(event.request.url);
  url.hostname = "i.pximg.net";
  let request = new Request(url, event.request);
  event.respondWith(
    fetch(request, {
      headers: {
        'Referer': 'https://www.pixiv.net/',
        'User-Agent': 'Cloudflare Workers'
      }
    })
  );
});

如何修复 CORS 错误?

您应该仔细阅读 CORS 以了解您收到此错误的原因,然后修复应该很简单(设置额外的 headers)- https://web.dev/cross-origin-resource-sharing/