No 'Access-Control-Allow-Origin' header is present error from JS

The issue was that the worker didn’t answer to OPTIONS request.

The solution was to handle these type of requests with

if (request.method === "OPTIONS") {
    return handleOptions(request)
  }

and

function handleOptions(request) {
  if (request.headers.get("Origin") !== null &&
      request.headers.get("Access-Control-Request-Method") !== null &&
      request.headers.get("Access-Control-Request-Headers") !== null) {
    // Handle CORS pre-flight request.
    return new Response(null, {
      headers: corsHeaders
    })
  } else {
    // Handle standard OPTIONS request.
    return new Response(null, {
      headers: {
        "Allow": "GET, OPTIONS",
      }
    })
  }
}

with

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, OPTIONS",
  "Access-Control-Allow-Headers": "*",
}

Clearly Access-Control-Allow-Origin and Access-Control-Allow-Headers adding only the

Reference Handling preflight requests - #3 by webchad

2 Likes