Browse Source

Merge pull request #76 from sindresorhus/content-length

Add content-length header in POST
http2
Vsevolod Strukchinsky 10 years ago
parent
commit
ef840f7c50
  1. 13
      index.js
  2. 2
      readme.md
  3. 28
      test/test-post.js

13
index.js

@ -61,7 +61,16 @@ function got(url, opts, cb) {
}
if (body) {
if (typeof body !== 'string' && !Buffer.isBuffer(body) && !isStream.readable(body)) {
throw new GotError('options.body must be a ReadableStream, string or Buffer');
}
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';
@ -81,10 +90,6 @@ function got(url, opts, cb) {
throw new GotError('got can not be used as stream when options.json is used');
}
if (body && !(typeof body === 'string' || Buffer.isBuffer(body) || isStream.readable(body))) {
throw new GotError('options.body must be a ReadableStream, string or Buffer');
}
function get(url, opts, cb) {
var parsedUrl = typeof url === 'string' ? urlLib.parse(prependHttp(url)) : url;
var fn = parsedUrl.protocol === 'https:' ? https : http;

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