fix cors not handling multi origins
This commit is contained in:
@@ -2,7 +2,7 @@ import { HttpError } from "./error.ts"
|
||||
|
||||
type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "OPTIONS" | "PATCH"
|
||||
|
||||
const ALLOWED_ORIGINS = ["http://localhost:5173"]
|
||||
const ALLOWED_ORIGINS = ["http://localhost:5173", "http://127.0.0.1:5173"]
|
||||
|
||||
function httpHandler<Route extends string>(
|
||||
handler: (request: Bun.BunRequest<Route>) => Promise<Response>,
|
||||
@@ -23,7 +23,8 @@ function httpHandler<Route extends string>(
|
||||
response = new Response(undefined, { status: 500 })
|
||||
}
|
||||
}
|
||||
for (const origin of ALLOWED_ORIGINS) {
|
||||
const origin = request.headers.get("Origin")
|
||||
if (origin && ALLOWED_ORIGINS.includes(origin)) {
|
||||
response.headers.set("Access-Control-Allow-Origin", origin)
|
||||
}
|
||||
response.headers.set("Access-Control-Allow-Credentials", "true")
|
||||
@@ -35,16 +36,21 @@ function preflightHandler<Route extends string>({
|
||||
allowedMethods,
|
||||
allowedHeaders,
|
||||
}: { allowedMethods: HttpMethod[]; allowedHeaders: string[] }) {
|
||||
return async (request: Bun.BunRequest<Route>) =>
|
||||
new Response(undefined, {
|
||||
return async (request: Bun.BunRequest<Route>) => {
|
||||
const origin = request.headers.get("Origin")
|
||||
const headers: Record<string, string> = {
|
||||
"Access-Control-Allow-Methods": allowedMethods.join(", "),
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
"Access-Control-Allow-Headers": allowedHeaders.join(", "),
|
||||
}
|
||||
if (origin && ALLOWED_ORIGINS.includes(origin)) {
|
||||
headers["Access-Control-Allow-Origin"] = origin
|
||||
}
|
||||
return new Response(undefined, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": ALLOWED_ORIGINS.join(", "),
|
||||
"Access-Control-Allow-Methods": allowedMethods.join(", "),
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
"Access-Control-Allow-Headers": allowedHeaders.join(", "),
|
||||
},
|
||||
headers,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export { httpHandler, preflightHandler }
|
||||
|
Reference in New Issue
Block a user