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'
      }
    })
  );
});

Can someone fix my code to allow cors?

You need to add the Access-Control-Allow-Origin: * header to your response. For example:

export default {
    async fetch(request) {
        const requestUrl = new URL(request.url)
        requestUrl.hostname = 'i.pximg.net'        
        const response = await fetch(requestUrl, {
            headers: {
                'Referer': 'https://www.pixiv.net/',
                'User-Agent': 'Cloudflare Workers'
            }
        })
        const responseHeaders = new Headers(response.headers)
        responseHeaders.set('Access-Control-Allow-Origin', '*')
        return new Response(response.body, {
            headers: responseHeaders,
            status: response.status,
            statusText: response.statusText
        })
    }
}
2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.