fix CORS
This commit is contained in:
parent
71fc07133a
commit
632e7979a2
|
|
@ -97,7 +97,21 @@ export class TldrawDurableObject {
|
||||||
|
|
||||||
// `fetch` is the entry point for all requests to the Durable Object
|
// `fetch` is the entry point for all requests to the Durable Object
|
||||||
fetch(request: Request): Response | Promise<Response> {
|
fetch(request: Request): Response | Promise<Response> {
|
||||||
return this.router.fetch(request)
|
try {
|
||||||
|
return this.router.fetch(request)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error in DO fetch:', err);
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
error: 'Internal Server Error',
|
||||||
|
message: (err as Error).message
|
||||||
|
}), {
|
||||||
|
status: 500,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Access-Control-Allow-Origin': '*'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// what happens when someone tries to connect to this room?
|
// what happens when someone tries to connect to this room?
|
||||||
|
|
|
||||||
|
|
@ -133,3 +133,39 @@ const router = AutoRouter<IRequest, [env: Environment, ctx: ExecutionContext]>({
|
||||||
|
|
||||||
// export our router for cloudflare
|
// export our router for cloudflare
|
||||||
export default router
|
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;
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue