Skip to content

Commit

Permalink
Merge pull request #13 from nyaomaru/deno-study-9
Browse files Browse the repository at this point in the history
study: CORS
  • Loading branch information
nyaomaru authored Aug 12, 2024
2 parents 4acdedd + 3755048 commit dbaf249
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions src/routes/_middleware.ts
Original file line number Diff line number Diff line change
@@ -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<State>,
) {
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;
}

0 comments on commit dbaf249

Please sign in to comment.