Skip to content

Commit

Permalink
Set content-length header to zero when doing a PUT request with no …
Browse files Browse the repository at this point in the history
…body (#584)

Fixes #582
  • Loading branch information
szmarczak authored and sindresorhus committed Aug 24, 2018
1 parent 716b914 commit 9a966ec
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
10 changes: 4 additions & 6 deletions source/request-as-event-emitter.js
Expand Up @@ -162,12 +162,10 @@ module.exports = options => {
try {
uploadBodySize = await getBodySize(options);

if (
uploadBodySize > 0 &&
is.undefined(options.headers['content-length']) &&
is.undefined(options.headers['transfer-encoding'])
) {
options.headers['content-length'] = uploadBodySize;
if (is.undefined(options.headers['content-length']) && is.undefined(options.headers['transfer-encoding'])) {
if (uploadBodySize > 0 || options.method === 'PUT') {
options.headers['content-length'] = uploadBodySize;
}
}

for (const hook of options.hooks.beforeRequest) {
Expand Down
10 changes: 9 additions & 1 deletion test/headers.js
Expand Up @@ -80,7 +80,7 @@ test('transform names to lowercase', async t => {
t.is(headers['user-agent'], 'test');
});

test('zero content-length', async t => {
test('setting content-length to 0', async t => {
const {body} = await got(s.url, {
headers: {
'content-length': 0
Expand All @@ -91,6 +91,14 @@ test('zero content-length', async t => {
t.is(headers['content-length'], '0');
});

test('sets content-length to 0 when requesting PUT with empty body', async t => {
const {body} = await got(s.url, {
method: 'PUT'
});
const headers = JSON.parse(body);
t.is(headers['content-length'], '0');
});

test('form-data manual content-type', async t => {
const form = new FormData();
form.append('a', 'b');
Expand Down

0 comments on commit 9a966ec

Please sign in to comment.