Skip to content

Commit

Permalink
fix(fetch): send content-length:0 if the body is empty for POST/PUT e…
Browse files Browse the repository at this point in the history
…tc requests
  • Loading branch information
ardatan committed Mar 21, 2024
1 parent 77d550e commit dfb4290
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .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
6 changes: 6 additions & 0 deletions packages/node-fetch/src/Request.ts
Expand Up @@ -81,6 +81,12 @@ export class PonyfillRequest<TJSON = any> extends PonyfillBody<TJSON> implements
}

const contentLengthInHeaders = this.headers.get('content-length');

if (bodyInit == null && !contentLengthInHeaders) {
this.contentLength = 0;
this.headers.set('content-length', '0');
}

if (!contentLengthInHeaders) {
if (this.contentLength) {
this.headers.set('content-length', this.contentLength.toString());
Expand Down
31 changes: 31 additions & 0 deletions packages/server/test/node.spec.ts
Expand Up @@ -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');
});
});
});
});
Expand Down

0 comments on commit dfb4290

Please sign in to comment.