From 37550483adc4202b667f386bded712eab477f275 Mon Sep 17 00:00:00 2001 From: nyaomaru Date: Mon, 12 Aug 2024 10:59:49 +0900 Subject: [PATCH] study: CORS --- src/routes/_middleware.ts | 44 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/src/routes/_middleware.ts b/src/routes/_middleware.ts index d26be09..6c0c4d3 100644 --- a/src/routes/_middleware.ts +++ b/src/routes/_middleware.ts @@ -1,15 +1,55 @@ import { FreshContext } from "$fresh/server.ts"; +const HTTP_HEADER = { + ACCESS_CONTROL_ALLOW_ORIGIN: "Access-Control-Allow-Origin", + ACCESS_CONTROL_ALLOW_METHODS: "Access-Control-Allow-Methods", + ACCESS_CONTROL_ALLOW_CREDENTIALS: "Access-Control-Allow-Credentials", + ACCESS_CONTROL_ALLOW_HEADERS: "Access-Control-Allow-Headers", +}; + +const HTTP_METHOD = { + GET: "GET", + PUT: "PUT", + POST: "POST", + DELETE: "DELETE", + OPTIONS: "OPTIONS", +}; + interface State { data: string; } export async function handler( - _req: Request, + req: Request, ctx: FreshContext, ) { - ctx.state.data = "myData"; + if (req.method == HTTP_METHOD.OPTIONS) { + const resp = new Response(null, { + status: 204, + }); + const origin = req.headers.get("Origin") || "*"; + const headers = resp.headers; + headers.set(HTTP_HEADER.ACCESS_CONTROL_ALLOW_ORIGIN, origin); + headers.set(HTTP_HEADER.ACCESS_CONTROL_ALLOW_METHODS, HTTP_METHOD.DELETE); + return resp; + } + + const origin = req.headers.get("Origin") || "*"; const resp = await ctx.next(); + const headers = resp.headers; + + headers.set(HTTP_HEADER.ACCESS_CONTROL_ALLOW_ORIGIN, origin); + headers.set(HTTP_HEADER.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); + headers.set( + HTTP_HEADER.ACCESS_CONTROL_ALLOW_HEADERS, + "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With", + ); + headers.set( + HTTP_HEADER.ACCESS_CONTROL_ALLOW_METHODS, + `${HTTP_METHOD.POST}, ${HTTP_METHOD.OPTIONS}, ${HTTP_METHOD.GET}, ${HTTP_METHOD.DELETE}, ${HTTP_METHOD.PUT}`, + ); + + ctx.state.data = "myData"; resp.headers.set("server", "fresh server"); return resp; }