From e087330f49be522bbdb0a3fcbc3d013615c1f9a3 Mon Sep 17 00:00:00 2001 From: Jeff Emmett <46964190+Jeff-Emmett@users.noreply.github.com> Date: Sat, 7 Dec 2024 15:03:53 -0500 Subject: [PATCH] fix CORS --- worker/TldrawDurableObject.ts | 11 ++++++++++- worker/worker.ts | 36 ----------------------------------- 2 files changed, 10 insertions(+), 37 deletions(-) diff --git a/worker/TldrawDurableObject.ts b/worker/TldrawDurableObject.ts index a362bca..79640ef 100644 --- a/worker/TldrawDurableObject.ts +++ b/worker/TldrawDurableObject.ts @@ -136,7 +136,16 @@ export class TldrawDurableObject { room.handleSocketConnect({ sessionId, socket: serverWebSocket }) // return the websocket connection to the client - return new Response(null, { status: 101, webSocket: clientWebSocket }) + return new Response(null, { + status: 101, + webSocket: clientWebSocket, + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, UPGRADE', + 'Access-Control-Allow-Headers': '*', + 'Access-Control-Allow-Credentials': 'true' + } + }); } getRoom() { diff --git a/worker/worker.ts b/worker/worker.ts index c319f2d..00456a0 100644 --- a/worker/worker.ts +++ b/worker/worker.ts @@ -125,39 +125,3 @@ const router = AutoRouter({ // export our router for cloudflare export default router - -const corsHeaders = { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type, Authorization', - 'Access-Control-Max-Age': '86400', -}; - -// Add CORS headers to all responses -function handleCors(request: Request) { - // Handle preflight requests - if (request.method === 'OPTIONS') { - return new Response(null, { - headers: corsHeaders - }); - } - - return null; -} - -// Modify the fetch handler -async function handleRequest(request: Request) { - // Handle CORS preflight - const corsResult = handleCors(request); - if (corsResult) return corsResult; - - // Handle the actual request - const response = await router.handle(request); - - // Add CORS headers to the response - Object.entries(corsHeaders).forEach(([key, value]) => { - response.headers.set(key, value); - }); - - return response; -}