diff --git a/.changeset/thick-feet-own.md b/.changeset/thick-feet-own.md new file mode 100644 index 00000000000..51a5e641605 --- /dev/null +++ b/.changeset/thick-feet-own.md @@ -0,0 +1,5 @@ +--- +"@whatwg-node/node-fetch": patch +--- + +Send Content-Length:0 if the body is empty in POSTlike requests diff --git a/packages/node-fetch/src/Request.ts b/packages/node-fetch/src/Request.ts index 63e0e18d87a..0bc0e608c1d 100644 --- a/packages/node-fetch/src/Request.ts +++ b/packages/node-fetch/src/Request.ts @@ -81,6 +81,12 @@ export class PonyfillRequest extends PonyfillBody implements } const contentLengthInHeaders = this.headers.get('content-length'); + + if (this.body == null && !contentLengthInHeaders) { + this.contentLength = 0; + this.headers.set('content-length', '0'); + } + if (!contentLengthInHeaders) { if (this.contentLength) { this.headers.set('content-length', this.contentLength.toString()); diff --git a/packages/server/test/node.spec.ts b/packages/server/test/node.spec.ts index d8311622dfb..5f1bfafbdad 100644 --- a/packages/server/test/node.spec.ts +++ b/packages/server/test/node.spec.ts @@ -202,6 +202,37 @@ describe('Node Specific Cases', () => { const resJson = await response.json(); expect(resJson.contentLength).toBe('11'); }); + + it('sends content-length correctly if body is nullish', async () => { + const serverAdapter = createServerAdapter(req => { + return Response.json({ + contentLength: req.headers.get('content-length'), + }); + }); + testServer.addOnceHandler(serverAdapter); + const response = await fetch(testServer.url, { + method: 'POST', + }); + + const resJson = await response.json(); + expect(resJson.contentLength).toBe('0'); + }); + + it('sends content-length correctly if body is empty', async () => { + const serverAdapter = createServerAdapter(req => { + return Response.json({ + contentLength: req.headers.get('content-length'), + }); + }); + testServer.addOnceHandler(serverAdapter); + const response = await fetch(testServer.url, { + method: 'POST', + body: '', + }); + + const resJson = await response.json(); + expect(resJson.contentLength).toBe('0'); + }); }); }); });