diff --git a/index.js b/index.js index 88862a4..8466622 100644 --- a/index.js +++ b/index.js @@ -62,6 +62,11 @@ function got(url, opts, cb) { if (body) { opts.method = opts.method || 'POST'; + + if (!opts.headers['content-length'] && !opts.headers['transfer-encoding'] && !isStream.readable(body)) { + var length = typeof body === 'string' ? Buffer.byteLength(body) : body.length; + opts.headers['content-length'] = length; + } } opts.method = opts.method || 'GET'; diff --git a/readme.md b/readme.md index bfb48ab..9085cdc 100644 --- a/readme.md +++ b/readme.md @@ -70,6 +70,8 @@ _This option and stream mode are mutually exclusive._ Body, that will be sent with `POST` request. If present in `options` and `options.method` is not set - `options.method` will be set to `POST`. +If `content-length` or `transfer-encoding` is not set in `options.headers` and body is String or Buffer - `content-length` will be set to body length. + ###### encoding Type: `string`, `null` diff --git a/test/test-post.js b/test/test-post.js index a0b7b62..9dabbbe 100644 --- a/test/test-post.js +++ b/test/test-post.js @@ -9,6 +9,10 @@ s.on('/', function (req, res) { req.pipe(res); }); +s.on('/headers', function (req, res) { + res.end(JSON.stringify(req.headers)); +}); + s.on('/method', function (req, res) { res.setHeader('method', req.method); res.end(); @@ -89,6 +93,30 @@ test('throws on write to stream with body specified', function (t) { setTimeout(t.end.bind(t), 10); }); +test('post have content-length header to string', function (t) { + t.plan(5); + + got(s.url + '/headers', {body: 'wow', json: true}, function (err, headers) { + t.equal(headers['content-length'], '3'); + }); + + got(s.url + '/headers', {body: new Buffer('wow'), json: true}, function (err, headers) { + t.equal(headers['content-length'], '3'); + }); + + got(s.url + '/headers', {body: from2Array(['wow']), json: true}, function (err, headers) { + t.equal(headers['content-length'], undefined); + }); + + got(s.url + '/headers', {body: 'wow', json: true, headers: {'content-length': '10'}}, function (err, headers) { + t.equal(headers['content-length'], '10'); + }); + + got(s.url + '/headers', {body: '3\r\nwow\r\n0\r\n', json: true, headers: {'transfer-encoding': 'chunked'}}, function (err, headers) { + t.equal(headers['content-length'], undefined); + }); +}); + test('cleanup', function (t) { s.close(); t.end();