| 3 | }); |
| 4 | |
| 5 | async function handleRequest(request) { |
| 6 | const url = new URL(request.url); |
| 7 | const fetchAPI = request.url.replace(url.host, 'api.openai.com'); |
| 8 | |
| 9 | // 部分代理工具,请求由浏览器发起,跨域请求时会先发送一个 preflight 进行检查,也就是 OPTIONS 请求 |
| 10 | // 需要响应该请求,否则后续的 POST 会失败 |
| 11 | const corsHeaders = { |
| 12 | 'Access-Control-Allow-Origin': '*', |
| 13 | 'Access-Control-Allow-Methods': 'OPTIONS', |
| 14 | 'Access-Control-Allow-Headers': '*', |
| 15 | }; |
| 16 | if (request.method === 'OPTIONS') return new Response(null, { headers: corsHeaders }); |
| 17 | |
| 18 | const authKey = request.headers.get('Authorization'); |
| 19 | if (!authKey) return new Response("Not allowed", { status: 403 }); |
| 20 | |
| 21 | let contentType = request.headers.get('Content-Type') |
| 22 | if (contentType && contentType.startsWith("multipart/form-data")) { |
| 23 | let newRequest = new Request(fetchAPI, request); |
| 24 | return await fetch(newRequest); |
| 25 | } |
| 26 | |
| 27 | let body; |
| 28 | if (request.method === 'POST') body = await request.json(); |
| 29 | |
| 30 | const payload = { |
| 31 | method: request.method, |
| 32 | headers: { |
| 33 | "Content-Type": "application/json", |
| 34 | Authorization: authKey, |
| 35 | }, |
| 36 | body: typeof body === 'object' ? JSON.stringify(body) : '{}', |
| 37 | }; |
| 38 | // 在 Cloudflare 中,HEAD 和 GET 请求带 body 会报错 |
| 39 | if (['HEAD', 'GET'].includes(request.method)) delete payload.body; |
| 40 | |
| 41 | // 入参中如果包含了 stream=true,则表现形式为流式输出 |
| 42 | const response = await fetch(fetchAPI, payload); |
| 43 | if (body && body.stream !== true) { |
| 44 | const results = await response.json(); |
| 45 | return new Response(JSON.stringify(results), { |
| 46 | status: response.status, |
| 47 | headers: { |
| 48 | "Content-Type": "application/json", |
| 49 | }, |
| 50 | }); |
| 51 | } else { |
| 52 | return new Response(response.body, { |
| 53 | status: response.status, |
| 54 | statusText: response.statusText, |
| 55 | headers: response.headers, |
| 56 | }); |
| 57 | } |
| 58 | } |