From b0849b4a02268dc5a018ad2101121c3c8321504c Mon Sep 17 00:00:00 2001 From: Graham Floyd Date: Tue, 21 Mar 2023 05:34:43 -0500 Subject: [PATCH] fix(ClientRequest): set null body for GET/HEAD requests (#364) Creating a GET or HEAD fetch Request with a non-null/undefined body throws a `TypeError`. Some (possibly misbehaving) clients (notably the Stripe Node library) write an empty string to the request buffer even for GET/HEAD, causing a failure when intercepting any of those requests. A test has been added to `createRequest.test.ts` that fails without this change. Co-authored-by: Graham Floyd --- .../ClientRequest/utils/createRequest.test.ts | 23 +++++++++++++++++++ .../ClientRequest/utils/createRequest.ts | 9 ++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/interceptors/ClientRequest/utils/createRequest.test.ts b/src/interceptors/ClientRequest/utils/createRequest.test.ts index 4702a3d2..a6b1ccb7 100644 --- a/src/interceptors/ClientRequest/utils/createRequest.test.ts +++ b/src/interceptors/ClientRequest/utils/createRequest.test.ts @@ -60,3 +60,26 @@ it('creates a fetch Request with an empty body', async () => { expect(request.headers.get('Accept')).toBe('application/json') expect(request.body).toBe(null) }) + +it('creates a fetch Request with an empty string body', async () => { + const clientRequest = new NodeClientRequest( + [ + new URL('https://api.github.com'), + { + method: 'HEAD', + }, + () => {}, + ], + { + emitter, + log, + } + ) + clientRequest.write('') + + const request = createRequest(clientRequest) + + expect(request.method).toBe('HEAD') + expect(request.url).toBe('https://api.github.com/') + expect(request.body).toBe(null) +}) diff --git a/src/interceptors/ClientRequest/utils/createRequest.ts b/src/interceptors/ClientRequest/utils/createRequest.ts index aba6efce..e7f76939 100644 --- a/src/interceptors/ClientRequest/utils/createRequest.ts +++ b/src/interceptors/ClientRequest/utils/createRequest.ts @@ -21,10 +21,15 @@ export function createRequest(clientRequest: NodeClientRequest): Request { } } + const method = clientRequest.method || 'GET' + return new Request(clientRequest.url, { - method: clientRequest.method || 'GET', + method, headers, credentials: 'same-origin', - body: clientRequest.requestBuffer, + body: + method === 'HEAD' || method === 'GET' + ? null + : clientRequest.requestBuffer, }) }