Created
November 4, 2020 01:12
-
-
Save rchrd2/dc74d4802050e3af62a125b048a53c71 to your computer and use it in GitHub Desktop.
Cloudflare worker CORS proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// forked from: https://github.com/chebyrash/cors | |
addEventListener("fetch", event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
async function handleRequest(request) { | |
try { | |
const url = new URL(request.url); | |
if (url.pathname === "/") { | |
return new Response(`{"usage": "${url.origin}/<url>"}`); | |
} | |
function addHeaders(response) { | |
response.headers.set("Access-Control-Allow-Origin", "*"); | |
response.headers.set("Access-Control-Allow-Credentials", "true"); | |
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); | |
response.headers.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); | |
} | |
let response; | |
if (request.method == "OPTIONS") { | |
response = new Response(""); | |
addHeaders(response); | |
return response; | |
} | |
response = await fetch(request.url.slice(url.origin.length + 1), { | |
method: request.method, | |
headers: request.headers, | |
redirect: "follow", | |
body: request.body | |
}); | |
response = new Response(response.body, response) | |
addHeaders(response); | |
return response; | |
} catch (e) { | |
return new Response(e.stack || e, {status: 500}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment