// Cloudflare Worker: Gemini API Proxy export default { async fetch(request, env, ctx) { // 1. CORS 설정 (어느 웹사이트에서든 요청할 수 있도록 허용) const corsHeaders = { 'Access-Control-Allow-Origin': '*', // 필요하다면 'https://내사이트.웹.app' 등 특정 도메인만 허용하도록 변경 가능 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', }; // 브라우저의 OPTIONS 프리플라이트 요청(CORS 사전 검사) 처리 if (request.method === 'OPTIONS') { return new Response(null, { headers: corsHeaders }); } // 2. 오직 POST 요청만 처리 if (request.method !== 'POST') { return new Response(JSON.stringify({ error: 'POST requests only' }), { status: 405, // Method Not Allowed headers: { ...corsHeaders, 'Content-Type': 'application/json' }, }); } try { // 3. 클라이언트(내 웹사이트)에서 보낸 프롬프트 데이터 꺼내기 const requestData = await request.json(); // 4. Gemini API 주소 설정 // 환경 변수로 등록한 GEMINI_API_KEY를 안전하게 가져옴 const apiKey = env.GEMINI_API_KEY; if (!apiKey) { throw new Error('Server Configuration Error: GEMINI_API_KEY is not set in Environment Variables.'); } const geminiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`; // 5. 서버(Worker)가 대신 Gemini에게 요청 보내기 const geminiResponse = await fetch(geminiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, // 클라이언트에서 보낸 데이터(contents 형식) 그대로 Gemini로 전송 body: JSON.stringify(requestData) }); // 6. 응답 데이터 파싱 const data = await geminiResponse.json(); if (!geminiResponse.ok) { return new Response(JSON.stringify({ error: 'Gemini API Error', details: data }), { status: geminiResponse.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, }); } // 7. Gemini의 결과를 다시 내 프론트엔드로 전달! return new Response(JSON.stringify(data), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, }); } catch (error) { console.error('Worker Error:', error); return new Response(JSON.stringify({ error: error.message || 'Internal Server Error' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, }); } }, };