Browse Source

Add content-length header in POST

If:
 - not already defined
 - 'transfer-encoding' is not used
 - body is not Stream

Closes #71
http2
Vsevolod Strukchinsky 10 years ago
parent
commit
87d98e1f46
  1. 5
      index.js
  2. 2
      readme.md
  3. 28
      test/test-post.js

5
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';

2
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`

28
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();

Loading…
Cancel
Save