'How to set CORS header in cloudflare workers?

I'm using cloudflare workers to create a reverse proxy but I can't use it to embed on main domain cause it gives CORS error:

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.

here's the code in 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'
      }
    })
  );
});

How can I fix the CORS error?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source