Skip to content

Commit 3149340

Browse files
committedDec 15, 2019
Fix content-length header not being set when using custom content-type
Fixes #996
1 parent 7bf92f4 commit 3149340

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed
 

‎source/normalize-arguments.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ export const normalizeRequestArguments = async (options: NormalizedOptions): Pro
377377
// Content-Length header field when the request message does not contain
378378
// a payload body and the method semantics do not anticipate such a
379379
// body.
380-
if (noContentType && is.undefined(headers['transfer-encoding'])) {
380+
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding'])) {
381381
if (
382382
(options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') &&
383383
!is.undefined(uploadBodySize)

‎test/post.ts

+29
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,22 @@ test('`content-length` header with string body', withServer, async (t, server, g
113113
t.is(headers['content-length'], '3');
114114
});
115115

116+
test('`content-length` header with json body', withServer, async (t, server, got) => {
117+
server.post('/', echoHeaders);
118+
119+
const {body} = await got.post({json: {foo: 'bar'}});
120+
const headers = JSON.parse(body);
121+
t.is(headers['content-length'], '13');
122+
});
123+
124+
test('`content-length` header with form body', withServer, async (t, server, got) => {
125+
server.post('/', echoHeaders);
126+
127+
const {body} = await got.post({form: {foo: 'bar'}});
128+
const headers = JSON.parse(body);
129+
t.is(headers['content-length'], '7');
130+
});
131+
116132
test('`content-length` header with Buffer body', withServer, async (t, server, got) => {
117133
server.post('/', echoHeaders);
118134

@@ -143,6 +159,19 @@ test('`content-length` header is not overriden', withServer, async (t, server, g
143159
t.is(headers['content-length'], '10');
144160
});
145161

162+
test('`content-length` header is present when using custom content-type', withServer, async (t, server, got) => {
163+
server.post('/', echoHeaders);
164+
165+
const {body} = await got.post({
166+
json: {foo: 'bar'},
167+
headers: {
168+
'content-type': 'custom'
169+
}
170+
});
171+
const headers = JSON.parse(body);
172+
t.is(headers['content-length'], '13');
173+
});
174+
146175
test('`content-length` header disabled for chunked transfer-encoding', withServer, async (t, server, got) => {
147176
server.post('/', echoHeaders);
148177

0 commit comments

Comments
 (0)
Please sign in to comment.