Skip to content

Commit

Permalink
Add content-length header in POST
Browse files Browse the repository at this point in the history
If:
 - not already defined
 - 'transfer-encoding' is not used
 - body is not Stream

Closes #71
  • Loading branch information
floatdrop committed Jun 25, 2015
1 parent c1923e1 commit 87d98e1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
28 changes: 28 additions & 0 deletions test/test-post.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit 87d98e1

Please sign in to comment.