Skip to content

Instantly share code, notes, and snippets.

@bcnzer
Last active December 12, 2019 09:19
Show Gist options
  • Select an option

  • Save bcnzer/c8201e4efc72c79bc29093991c91ef3e to your computer and use it in GitHub Desktop.

Select an option

Save bcnzer/c8201e4efc72c79bc29093991c91ef3e to your computer and use it in GitHub Desktop.

Revisions

  1. bcnzer revised this gist Nov 3, 2018. 1 changed file with 1 addition and 2 deletions.
    3 changes: 1 addition & 2 deletions workerOptions.js
    Original file line number Diff line number Diff line change
    @@ -19,8 +19,7 @@ async function handleRequest(event) {
    return new Response('', { headers:corsHeaders })
    }

    ...

    // For any other request, simple get it and return it
    const response = await fetch(event.request)
    return response
    }
  2. bcnzer created this gist Nov 3, 2018.
    47 changes: 47 additions & 0 deletions workerOptions.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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 })
    }

    ...

    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
    }