-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #13 from nyaomaru/deno-study-9
study: CORS
- Loading branch information
Showing
1 changed file
with
42 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |