From d6b7a1794738b2cf250a1acf11b3351a4860fb7d Mon Sep 17 00:00:00 2001 From: Kevin Whitley Date: Tue, 2 Apr 2024 16:29:21 -0500 Subject: [PATCH] fix #233 - cors eats status message --- src/cors.spec.ts | 9 +++++++++ src/cors.ts | 17 ++++++++--------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/cors.spec.ts b/src/cors.spec.ts index 35481f2..f9e81cd 100644 --- a/src/cors.spec.ts +++ b/src/cors.spec.ts @@ -236,6 +236,15 @@ describe('cors(options?: CorsOptions)', () => { expect(corsified.headers.getSetCookie().length).toBe(2) }) + it('will preserve existing status codes', async () => { + const { corsify } = cors() + const response = new Response(null, { status: 403 }) + const corsified = corsify(response.clone()) + + expect(response.status).toBe(403) + expect(corsified.status).toBe(403) + }) + it('will not modify a websocket request', async () => { const { corsify } = cors() const response = new WebSocketResponse(null, { status: 101 }) as Response diff --git a/src/cors.ts b/src/cors.ts index 8648969..9f6dbe7 100644 --- a/src/cors.ts +++ b/src/cors.ts @@ -77,15 +77,14 @@ export const cors = (options: CorsOptions = {}) => { || response.status == 101 ) return response - return new Response(response.body, { - ...response, - // @ts-expect-error - headers: [ - ...response.headers, - ['access-control-allow-origin', getAccessControlOrigin(request)], - ...Object.entries(corsHeaders), - ].filter(v => v[1]), - }) + const origin = getAccessControlOrigin(request) + if (origin) response.headers.append('access-control-allow-origin', origin) + + for (const [key, value] of Object.entries(corsHeaders)) { + if (value) response.headers.append(key, value) + } + + return response } // Return corsify and preflight methods.