-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathcors.ts
97 lines (91 loc) · 2.56 KB
/
cors.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import type { H3Event } from "../types";
import type { H3CorsOptions } from "../types/utils/cors";
import { noContent } from "./response";
import {
createAllowHeaderHeaders,
createCredentialsHeaders,
createExposeHeaders,
createMaxAgeHeader,
createMethodsHeaders,
createOriginHeaders,
resolveCorsOptions,
} from "./internal/cors";
export { isCorsOriginAllowed } from "./internal/cors";
/**
* Check if the incoming request is a CORS preflight request.
*/
export function isPreflightRequest(event: H3Event): boolean {
const origin = event.request.headers.get("origin");
const accessControlRequestMethod = event.request.headers.get(
"access-control-request-method",
);
return (
event.request.method === "OPTIONS" &&
!!origin &&
!!accessControlRequestMethod
);
}
/**
* Append CORS preflight headers to the response.
*/
export function appendCorsPreflightHeaders(
event: H3Event,
options: H3CorsOptions,
) {
const headers = {
...createOriginHeaders(event, options),
...createCredentialsHeaders(options),
...createMethodsHeaders(options),
...createAllowHeaderHeaders(event, options),
...createMaxAgeHeader(options),
};
for (const [key, value] of Object.entries(headers)) {
event.response.headers.append(key, value);
}
}
/**
* Append CORS headers to the response.
*/
export function appendCorsHeaders(event: H3Event, options: H3CorsOptions) {
const headers = {
...createOriginHeaders(event, options),
...createCredentialsHeaders(options),
...createExposeHeaders(options),
};
for (const [key, value] of Object.entries(headers)) {
event.response.headers.append(key, value);
}
}
/**
* Handle CORS for the incoming request.
*
* If the incoming request is a CORS preflight request, it will append the CORS preflight headers and send a 204 response.
*
* If return value is `true`, the request is handled and no further action is needed.
*
* @example
* const app = createApp();
* const router = createRouter();
* router.use("/", async (event) => {
* const corsRes = handleCors(event, {
* origin: "*",
* preflight: {
* statusCode: 204,
* },
* methods: "*",
* });
* if (corsRes) {
* return corsRes;
* }
* // Your code here
* });
*/
export function handleCors(event: H3Event, options: H3CorsOptions): false | "" {
const _options = resolveCorsOptions(options);
if (isPreflightRequest(event)) {
appendCorsPreflightHeaders(event, options);
return noContent(event, _options.preflight.statusCode);
}
appendCorsHeaders(event, options);
return false;
}