Skip to content

Instantly share code, notes, and snippets.

@kyupark
Forked from Kahtaf/index.js
Created March 2, 2023 18:41
Show Gist options
  • Save kyupark/dc6c02bb2b503f177bd9fd32751c13e5 to your computer and use it in GitHub Desktop.
Save kyupark/dc6c02bb2b503f177bd9fd32751c13e5 to your computer and use it in GitHub Desktop.
Create a simple CORS proxy with Cloudflare Workers to bypass CORS restrictions in the browser. Perfect for local development.
/**
* Create a simple CORS proxy with Cloudflare Workers
* to bypass cors restrictions in the browser.
* Example Usage: https://<worker_subdomain>.workers.dev/https://postman-echo.com/get?foo1=bar1&foo2=bar2
*/
addEventListener('fetch', event =>
event.respondWith(handleRequest(event.request))
)
const handleRequest = async request => {
let url = new URL(request.url)
let requestUrl = request.url.replace(`${url.origin}/`, '');
request = new Request(requestUrl, request)
if (request.headers.has('origin')) request.headers.delete('origin')
if (request.headers.has('referer')) request.headers.delete('referer')
let response = await fetch(request)
response = new Response(response.body, response)
response.headers.set('access-control-allow-origin', '*')
response.headers.set('access-control-allow-headers', '*')
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment