Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

增加跨域 #254

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 23 additions & 8 deletions src/routes/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,20 @@ const timeout = isNaN(+process.env.TIMEOUT!)
const passwordSet = process.env.PASSWORD || defaultEnv.PASSWORD

export async function POST({ request }: APIEvent) {

// 设置 CORS 相关的头
const headers = new Headers({
"Access-Control-Allow-Origin": "*", // 允许所有域
"Access-Control-Allow-Methods": "GET, POST, OPTIONS", // 允许的 HTTP 方法
"Access-Control-Allow-Headers": "Content-Type, Authorization", // 允许的 HTTP 头
"Content-Type": "application/json"
});

// 预检请求的处理
if (request.method === "OPTIONS") {
return new Response(null, { headers });
}

try {
const body: {
messages?: ChatMessage[]
Expand All @@ -74,21 +88,21 @@ export async function POST({ request }: APIEvent) {
const billings = await Promise.all(
splitKeys(key).map(k => fetchBilling(k))
)
return new Response(await genBillingsTable(billings))
return new Response(await genBillingsTable(billings), { headers })
} else {
throw new Error("没有填写 OpenAI API key,不会查询内置的 Key。")
}
} else if (content.startsWith("sk-")) {
const billings = await Promise.all(
splitKeys(content).map(k => fetchBilling(k))
)
return new Response(await genBillingsTable(billings))
return new Response(await genBillingsTable(billings), { headers })
}
}

const apiKey = randomKey(splitKeys(key))

if (!apiKey) throw new Error("没有填写 OpenAI API key,或者 key 填写错误。")
if (model) throw new Error(`模型指定错误:${model}`);

const encoder = new TextEncoder()
const decoder = new TextDecoder()
Expand Down Expand Up @@ -116,14 +130,15 @@ export async function POST({ request }: APIEvent) {
message: err.message
}
}),
{ status: 500 }
{ status: 500 , headers }
)
})

if (model) throw new Error("没有填写 OpenAI API key,或者 key 填写错误。")
if (!rawRes.ok) {
return new Response(rawRes.body, {
status: rawRes.status,
statusText: rawRes.statusText
statusText: rawRes.statusText,
headers
})
}

Expand Down Expand Up @@ -153,15 +168,15 @@ export async function POST({ request }: APIEvent) {
}
})

return new Response(stream)
return new Response(stream,{ headers})
} catch (err: any) {
return new Response(
JSON.stringify({
error: {
message: err.message
}
}),
{ status: 400 }
{ status: 400, headers }
)
}
}
Expand Down