From 314934035b49323fd7739ab6c92519c3565b0541 Mon Sep 17 00:00:00 2001 From: Szymon Marczak <36894700+szmarczak@users.noreply.github.com> Date: Sun, 15 Dec 2019 13:48:26 +0100 Subject: [PATCH] Fix `content-length` header not being set when using custom `content-type` Fixes #996 --- source/normalize-arguments.ts | 2 +- test/post.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/source/normalize-arguments.ts b/source/normalize-arguments.ts index 10ccdd2c4..5e98d7ad2 100644 --- a/source/normalize-arguments.ts +++ b/source/normalize-arguments.ts @@ -377,7 +377,7 @@ export const normalizeRequestArguments = async (options: NormalizedOptions): Pro // Content-Length header field when the request message does not contain // a payload body and the method semantics do not anticipate such a // body. - if (noContentType && is.undefined(headers['transfer-encoding'])) { + if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding'])) { if ( (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') && !is.undefined(uploadBodySize) diff --git a/test/post.ts b/test/post.ts index 635a9c5b7..7467178a1 100644 --- a/test/post.ts +++ b/test/post.ts @@ -113,6 +113,22 @@ test('`content-length` header with string body', withServer, async (t, server, g t.is(headers['content-length'], '3'); }); +test('`content-length` header with json body', withServer, async (t, server, got) => { + server.post('/', echoHeaders); + + const {body} = await got.post({json: {foo: 'bar'}}); + const headers = JSON.parse(body); + t.is(headers['content-length'], '13'); +}); + +test('`content-length` header with form body', withServer, async (t, server, got) => { + server.post('/', echoHeaders); + + const {body} = await got.post({form: {foo: 'bar'}}); + const headers = JSON.parse(body); + t.is(headers['content-length'], '7'); +}); + test('`content-length` header with Buffer body', withServer, async (t, server, got) => { server.post('/', echoHeaders); @@ -143,6 +159,19 @@ test('`content-length` header is not overriden', withServer, async (t, server, g t.is(headers['content-length'], '10'); }); +test('`content-length` header is present when using custom content-type', withServer, async (t, server, got) => { + server.post('/', echoHeaders); + + const {body} = await got.post({ + json: {foo: 'bar'}, + headers: { + 'content-type': 'custom' + } + }); + const headers = JSON.parse(body); + t.is(headers['content-length'], '13'); +}); + test('`content-length` header disabled for chunked transfer-encoding', withServer, async (t, server, got) => { server.post('/', echoHeaders);