CORS issue even when CORS header are added

My workers script with d1 binding, and '/api/view/customers_data' on GET request is succesful but sending POST request with body to '/api/add/customer' giving error

Fetch request
const response = await fetch( "https://xxxx.xxxxx.workers.dev/api/add/customer", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ id: xxx, cabin: xxxx, name: xxxx },) } );

// Workers Script

export default { async fetch(request, env, ctx) { const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': 'GET, POST', }; const { pathname } = new URL(request.url); try { if (pathname === "/api/view/customers_data") { const results = await env.DB.prepare( "SELECT * FROM customers_data " ).all(); return new Response(JSON.stringify(results), { headers: corsHeaders, }); }else if (pathname === "/api/add/customer") { const body = await request.json(); const results = await env.DB.prepare( "INSERT INTO customers_data (cabin, name, email, phone, gender) VALUES(?1, ?2, ?3, ?4, ?5)" ).bind(body.cabin, body.name, body.email, body.phone, body.gender).run(); return new Response(JSON.stringify(results), { headers: corsHeaders, }); } } catch (e) { return Response.json(e); } }); } };

//Error
Access to fetch at 'https://xxx.xxxx.workers.dev/api/add/customer' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Was this page helpful?