From 1ab9ca7939e624db8408ba4c6572f45309fd292f Mon Sep 17 00:00:00 2001 From: "Kevin R. Whitley" Date: Tue, 2 Apr 2024 16:38:05 -0500 Subject: [PATCH] fix #233 - cors eats status message (#234) * fix #233 - cors eats status message * CHANGELOG --- CHANGELOG.md | 2 ++ src/cors.spec.ts | 9 +++++++++ src/cors.ts | 17 ++++++++--------- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8d2063..e24346f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## Changelog +- **v5.0.6** + - fixed: corsify as replacing status codes (now mutates original response) - **v5.0.5** - fixed: corsify now properly ignores WebSocket responses - **v5.0.4** 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.