Bamboo
05/20/2023, 11:16 AMconst 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.meyer
05/20/2023, 12:48 PMmeyer
05/20/2023, 12:49 PMmeyer
05/20/2023, 12:51 PMcurl -v
the endpoint what response do you see?meyer
05/20/2023, 12:51 PMIsaac McFadyen | YYZ01
05/20/2023, 2:24 PMIsaac McFadyen | YYZ01
05/20/2023, 2:25 PMIsaac McFadyen | YYZ01
05/20/2023, 2:25 PMIsaac McFadyen | YYZ01
05/20/2023, 2:26 PMBamboo
05/20/2023, 3:30 PMBamboo
05/20/2023, 3:31 PMIsaac McFadyen | YYZ01
05/20/2023, 4:01 PMIsaac McFadyen | YYZ01
05/20/2023, 4:02 PMBamboo
05/21/2023, 5:09 AM