Correct way to set CORS in Cloudflare Workers

I've been trying to set CORS headers following the docs but it doesn't seem to be working for me.
import { appRouter, createTRPCContext } from 'trpc';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';

export default {
async fetch(request: Request): Promise<Response> {
console.log('requestHeaders:', JSON.stringify([...request.headers], null, 2));

const response = await fetchRequestHandler({
req: request,
endpoint: '/trpc',
router: appRouter,
createContext: createTRPCContext,
onError({ error, path }) {
console.error(`>>>>>> tRPC Error on '${path}'`, error);
},
});

const corsResponse = new Response(response.body, response);

corsResponse.headers.set('Access-Control-Allow-Origin', '*');
corsResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
corsResponse.headers.set('Access-Control-Allow-Headers', '*');

return corsResponse;
},
};
import { appRouter, createTRPCContext } from 'trpc';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';

export default {
async fetch(request: Request): Promise<Response> {
console.log('requestHeaders:', JSON.stringify([...request.headers], null, 2));

const response = await fetchRequestHandler({
req: request,
endpoint: '/trpc',
router: appRouter,
createContext: createTRPCContext,
onError({ error, path }) {
console.error(`>>>>>> tRPC Error on '${path}'`, error);
},
});

const corsResponse = new Response(response.body, response);

corsResponse.headers.set('Access-Control-Allow-Origin', '*');
corsResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
corsResponse.headers.set('Access-Control-Allow-Headers', '*');

return corsResponse;
},
};
Error: Access to fetch at 'http://127.0.0.1:8787/trpc/example.hello?batch=1&input=%7B%220%22%3A%7B%22json%22%3A%7B%22text%22%3A%22Yinka%22%7D%7D%7D' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
1 Reply
yinks
yinksOP15mo ago
Thank you @Leo That worked I added this line at the top of the function
// handle CORS preflight request
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
},
});
}
// handle CORS preflight request
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
},
});
}
Want results from more Discord servers?
Add your server