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.