Skip to content

Commit e09a9bd

Browse files
committed
Fix silent hang when returning cached response with FormData body from beforeRequest hook
Fixes #2232
1 parent 5bdd3d5 commit e09a9bd

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

source/core/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1280,7 +1280,9 @@ export default class Request extends Duplex implements RequestEvents<Request> {
12801280

12811281
private _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
12821282
if (!this._request || this._request.destroyed) {
1283-
// Probably the `ClientRequest` instance will throw
1283+
// When there's no request (e.g., using cached response from beforeRequest hook),
1284+
// we still need to call the callback to allow the stream to finish properly.
1285+
callback();
12841286
return;
12851287
}
12861288

test/hooks.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,29 @@ test('returning HTTP response from a beforeRequest hook', withServer, async (t,
390390
t.is(body, 'Hi!');
391391
});
392392

393+
test('returning HTTP response from a beforeRequest hook with FormData body', withServer, async (t, server, got) => {
394+
server.post('/', echoBody);
395+
396+
const form = new FormData();
397+
form.append('field', 'value');
398+
399+
const data = await got.post({
400+
body: form,
401+
hooks: {
402+
beforeRequest: [
403+
() => new Responselike({
404+
statusCode: 200,
405+
headers: {},
406+
body: Buffer.from('{"cached": "response"}'),
407+
url: '',
408+
}),
409+
],
410+
},
411+
}).json<{cached: string}>();
412+
413+
t.is(data.cached, 'response');
414+
});
415+
393416
test('beforeRedirect is called with options and response', withServer, async (t, server, got) => {
394417
server.get('/', echoHeaders);
395418
server.get('/redirect', redirectEndpoint);

0 commit comments

Comments
 (0)