Skip to content

Instantly share code, notes, and snippets.

@QuynhVir
Last active April 26, 2024 14:26
Show Gist options
  • Save QuynhVir/61dbe16d339edac97bd2f73e786e5361 to your computer and use it in GitHub Desktop.
Save QuynhVir/61dbe16d339edac97bd2f73e786e5361 to your computer and use it in GitHub Desktop.
Use this proxy by appending the URL you want to access to the base URL of this proxy. For example: https://our-corsproxy.site/https://somewhere.hates.cors/some-path?somequery=param
export default {
async fetch(request) {
function usageResponse() {
const usageHtml = `<!DOCTYPE html>
<html>
<head><title>CORS Proxy Service</title></head>
<body>
<h1>CORS Proxy Usage</h1>
<p>Use this proxy by appending the URL you want to access to the base URL of this proxy. For example:</p>
<code>https://our-corsproxy.site/https://somewhere.hates.cors/some-path?somequery=param</code>
</body>
</html>`;
return new Response(usageHtml, {
headers: {
"content-type": "text/html;charset=UTF-8",
},
});
}
const url = new URL(request.url);
const pathname = url.pathname;
const origin = request.headers.get("Origin");
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": origin ? origin : "*",
"Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, x-functions-key, Authorization",
"Access-Control-Max-Age": "86400",
}
});
}
if (pathname === '/') {
return usageResponse();
}
const apiUrl = pathname.substring(1);
try {
const proxyRequest = new Request(apiUrl, request);
proxyRequest.headers.set("Origin", new URL(apiUrl).origin);
let response = await fetch(proxyRequest);
response = new Response(response.body, response);
response.headers.set("Access-Control-Allow-Origin", origin ? origin : "*");
response.headers.set("Access-Control-Allow-Headers", "Content-Type, x-functions-key, Authorization");
response.headers.set("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS");
return response;
} catch (e) {
return new Response(`Fetch Error: ${e.message}`, {
status: 500
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment