feat: 添加CORS支持和流式响应处理,转发请求头以增强代理请求功能

This commit is contained in:
zhaoyingbo 2025-02-27 05:29:52 +00:00
parent 8d8bd5c305
commit ac3873c62d

View File

@ -16,8 +16,49 @@ export const manageModelProxyReq = async (ctx: Context) => {
}
const PROXY_URL =
"http://ms-13871-nstruct-lmdeploy-2-0109140455.kscn-tj5-prod2-cloudml.xiaomi.srv"
return fetch(PROXY_URL + new URL(req.url).pathname, {
// 发起代理请求
const response = await fetch(PROXY_URL + new URL(req.url).pathname, {
method: req.method,
body: req.body,
headers: {
// 转发必要的请求头
"Content-Type": headers.get("Content-Type") || "application/json",
Accept: headers.get("Accept") || "*/*",
},
})
// 获取原始响应的所有头信息
const responseHeaders = new Headers(response.headers)
// 添加CORS响应头
responseHeaders.set("Access-Control-Allow-Origin", "*")
responseHeaders.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
responseHeaders.set(
"Access-Control-Allow-Headers",
"Content-Type, Authorization"
)
responseHeaders.set("Access-Control-Expose-Headers", "Content-Type")
// 检查是否为流式响应
if (response.headers.get("Content-Type")?.includes("text/event-stream")) {
// 处理流式响应
const { readable, writable } = new TransformStream()
response.body
?.pipeTo(writable)
.catch((err) => logger.error("Stream error:", err))
return new Response(readable, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
} else {
// 处理非流式响应
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
})
}
}