Skip to content

Commit

Permalink
fix(ClientRequest): set null body for GET/HEAD requests (#364)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
gfloyd and Graham Floyd authored Mar 21, 2023
1 parent 42a1022 commit b0849b4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
23 changes: 23 additions & 0 deletions src/interceptors/ClientRequest/utils/createRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
9 changes: 7 additions & 2 deletions src/interceptors/ClientRequest/utils/createRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
}

0 comments on commit b0849b4

Please sign in to comment.