whisper.cat/weboasis/js/cloudflare_cors_header_proxy.min.js

50 lines
2.9 KiB
JavaScript
Raw Normal View History

2023-10-05 23:28:32 +11:00
async function handleRequest(a){const b=new URL(a.url);let c=b.searchParams.get("apiurl");null==c&&(c=API_URL),a=new Request(c,a),a.headers.set("Origin",new URL(c).origin);let d=await fetch(a);return d=new Response(d.body,d),d.headers.set("Access-Control-Allow-Origin","*"),d.headers.append("Vary","Origin"),d}function handleOptions(a){return null!==a.headers.get("Origin")&&null!==a.headers.get("Access-Control-Request-Method")&&null!==a.headers.get("Access-Control-Request-Headers")?new Response(null,{headers:corsHeaders}):new Response(null,{headers:{Allow:"GET, HEAD, POST, OPTIONS"}})}addEventListener("fetch",a=>{const b=a.request,c=new URL(b.url);c.pathname.startsWith(PROXY_ENDPOINT)?"OPTIONS"===b.method?a.respondWith(handleOptions(b)):"GET"===b.method||"HEAD"===b.method||"POST"===b.method?a.respondWith(handleRequest(b)):a.respondWith(new Response(null,{status:405,statusText:"Method Not Allowed"})):a.respondWith(rawHtmlResponse(DEMO_PAGE))});const corsHeaders={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, HEAD, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"},API_URL="https://workers-tooling.cf/demos/demoapi",PROXY_ENDPOINT="/corsproxy/";async function rawHtmlResponse(a){return new Response(a,{headers:{"content-type":"text/html;charset=UTF-8"}})}const DEMO_PAGE=`
<!DOCTYPE html>
<html>
<body>
<h1>API GET without CORS Proxy</h1>
<a target='_blank' href='https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful'>Shows TypeError: Failed to fetch since CORS is misconfigured</a>
<p id='noproxy-status'/>
<code id='noproxy'>Waiting</code>
<h1>API GET with CORS Proxy</h1>
<p id='proxy-status'/>
<code id='proxy'>Waiting</code>
<h1>API POST with CORS Proxy + Preflight</h1>
<p id='proxypreflight-status'/>
<code id='proxypreflight'>Waiting</code>
<script>
let reqs = {};
reqs.noproxy = async () => {
let response = await fetch('${API_URL}')
return await response.json()
}
reqs.proxy = async () => {
let response = await fetch(window.location.origin + '${PROXY_ENDPOINT}?apiurl=${API_URL}')
return await response.json()
}
reqs.proxypreflight = async () => {
const reqBody = {
msg: "Hello world!"
}
let response = await fetch(window.location.origin + '${PROXY_ENDPOINT}?apiurl=${API_URL}', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(reqBody),
})
return await response.json()
}
(async () => {
for (const [reqName, req] of Object.entries(reqs)) {
try {
let data = await req()
document.getElementById(reqName).innerHTML = JSON.stringify(data)
} catch (e) {
document.getElementById(reqName).innerHTML = e
}
}
})()
</script>
</body>
</html>`;