Skip to content

Instantly share code, notes, and snippets.

@bcnzer
Last active December 12, 2019 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcnzer/c8201e4efc72c79bc29093991c91ef3e to your computer and use it in GitHub Desktop.
Save bcnzer/c8201e4efc72c79bc29093991c91ef3e to your computer and use it in GitHub Desktop.
Cloudflare Worker example of how you can handle the OPTIONS verb and set some CORS details in the response header
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
/**
* Entry point of the worker
*/
async function handleRequest(event) {
// Generate the CORS headers I'll have to return with requests
const corsHeaders = setCorsHeaders(new Headers())
try {
const requestMethod = event.request.method
const requestUrl = new URL(event.request.url)
console.log(requestUrl)
// Always return the same CORS info
if(requestMethod === 'OPTIONS') {
return new Response('', { headers:corsHeaders })
}
// For any other request, simple get it and return it
const response = await fetch(event.request)
return response
}
catch (err) {
return new Response(err.stack, { status: 500, headers:corsHeaders })
}
}
/**
* Setup the CORS headers to the details
*/
function setCorsHeaders(headers) {
// Not a good idea to leave it to wildcard; I'm only doing so for initial testing/dev
headers.set('Access-Control-Allow-Origin', '*')
// Note the allowed verbs. You can add more
headers.set('Access-Control-Allow-Methods', 'POST, GET')
// You can manually add additional header values here. I added one for reCAPTCHA
headers.set('Access-Control-Allow-Headers', 'access-control-allow-headers, g-recaptcha')
headers.set('Access-Control-Max-Age', 1728000)
return headers
}
@vanhoutenbos
Copy link

headers.set('Access-Control-Allow-Origin', '*') How can one allow multiple origins all from https://*.contoso.com ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment