export interface Env {
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
const { pathname } = url;
// CORS headers
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
if (request.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
try {
if (pathname === "/api" && request.method === "GET") {
return Response.json({ message: "Hello from Cloudflare Workers!" }, { headers: corsHeaders });
}
if (pathname === "/api" && request.method === "POST") {
const body = await request.json();
// Process the data
return Response.json({ success: true, data: body }, { headers: corsHeaders });
}
return new Response("Not Found", { status: 404, headers: corsHeaders });
} catch (error) {
return Response.json({ error: "Internal Server Error" }, { status: 500, headers: corsHeaders });
}
},
};