Skip to content

Commit 2597d5a

Browse files
committed
optimized allow headers and methods normalizing
1 parent 2723b5c commit 2597d5a

File tree

1 file changed

+10
-11
lines changed
  • packages/event-handler/src/rest/middleware

1 file changed

+10
-11
lines changed

packages/event-handler/src/rest/middleware/cors.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ export const cors = (options?: CorsOptions): Middleware => {
5050
const allowedOrigins =
5151
typeof config.origin === 'string' ? [config.origin] : config.origin;
5252
const allowsWildcard = allowedOrigins.includes('*');
53+
const allowedMethods = config.allowMethods.map((method) =>
54+
method.toUpperCase()
55+
);
56+
const allowedHeaders = config.allowHeaders.map((header) =>
57+
header.toLowerCase()
58+
);
5359

5460
return async (_params, reqCtx, next) => {
5561
const requestOrigin = reqCtx.request.headers.get('Origin');
@@ -72,18 +78,11 @@ export const cors = (options?: CorsOptions): Middleware => {
7278
?.toLowerCase();
7379
if (
7480
!requestMethod ||
75-
!config.allowMethods
76-
.map((m) => m.toUpperCase())
77-
.includes(requestMethod) ||
81+
!allowedMethods.includes(requestMethod) ||
7882
!requestHeaders ||
7983
requestHeaders
8084
.split(',')
81-
.some(
82-
(header) =>
83-
!config.allowHeaders
84-
.map((h) => h.toLowerCase())
85-
.includes(header.trim())
86-
)
85+
.some((header) => !allowedHeaders.includes(header.trim()))
8786
) {
8887
await next();
8988
return;
@@ -106,10 +105,10 @@ export const cors = (options?: CorsOptions): Middleware => {
106105
config.maxAge.toString()
107106
);
108107
}
109-
config.allowMethods.forEach((method) => {
108+
allowedMethods.forEach((method) => {
110109
reqCtx.res.headers.append('access-control-allow-methods', method);
111110
});
112-
config.allowHeaders.forEach((header) => {
111+
allowedHeaders.forEach((header) => {
113112
reqCtx.res.headers.append('access-control-allow-headers', header);
114113
});
115114
return new Response(null, {

0 commit comments

Comments
 (0)