🔧 API 代理使用範例

正確的方式:透過後端伺服器呼叫 LLM API

❌ 您遇到的錯誤

CORS 錯誤:

Access to fetch at 'https://api.anthropic.com/v1/messages' from origin 'http://127.0.0.1:5000' has been blocked by CORS policy

Storage 錯誤:

Access to storage is not allowed from this context

🤔 為什麼會發生這個錯誤?

原因:
  • 安全限制:瀏覽器的 CORS 政策不允許直接從前端呼叫第三方 API
  • API 金鑰暴露:在前端直接使用 API 金鑰會洩露給所有使用者
  • Storage 限制:本地檔案 (file://) 無法使用 localStorage

🔄 錯誤 vs 正確的做法

❌ 錯誤:前端直接呼叫

// 不安全!API 金鑰會暴露 fetch('https://api.anthropic.com/v1/messages', { headers: { 'x-api-key': 'sk-ant-...' } })

✅ 正確:透過後端代理

// 安全!API 金鑰在後端 fetch('http://localhost:3000/api/llm/generate', { method: 'POST', body: JSON.stringify({...}) })

✅ 正確的使用方式

1. 測試 Claude API 連線

等待測試...

2. 使用 Claude 生成內容

等待生成...

3. 測試所有 LLM

等待測試...

📝 程式碼範例

測試連線

// 測試 Claude API 連線 async function testClaudeConnection() { try { const response = await fetch('http://localhost:3000/api/llm/test/claude', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); const result = await response.json(); console.log(result); } catch (error) { console.error(error); } }

生成內容

// 使用 Claude 生成內容 async function generateContent(prompt) { try { const response = await fetch('http://localhost:3000/api/llm/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: prompt, provider: 'claude', options: { temperature: 0.7, maxTokens: 2000 } }) }); const result = await response.json(); return result.content; } catch (error) { console.error(error); } }

⚙️ 設定步驟

1. 設定環境變數 (.env)
CLAUDE_API_KEY=your_claude_api_key_here CLAUDE_API_URL=https://api.anthropic.com/v1 CLAUDE_MODEL=claude-3-5-sonnet-20241022
2. 啟動後端伺服器
# 安裝依賴 npm install # 啟動開發伺服器 npm run dev # 或生產環境 npm start
3. 完成!

現在可以透過 http://localhost:3000/api/llm/* 安全地呼叫 LLM API 了