Browse Source

Close #15 PR: Implement body option.

http2
Vsevolod Strukchinsky 10 years ago
committed by Sindre Sorhus
parent
commit
2c8ee3fc91
  1. 17
      index.js
  2. 6
      readme.md
  3. 35
      test.js

17
index.js

@ -22,6 +22,13 @@ module.exports = function (url, opts, cb) {
var encoding = opts.encoding;
delete opts.encoding;
var body = opts.body;
delete opts.body;
if (body && opts.method === undefined) {
opts.method = 'POST';
}
// returns a proxy stream to the response
// if no callback has been provided
var proxy;
@ -47,7 +54,7 @@ module.exports = function (url, opts, cb) {
var fn = parsedUrl.protocol === 'https:' ? https : http;
var arg = assign({}, parsedUrl, opts);
var req = fn.get(arg, function (response) {
var req = fn.request(arg, function (response) {
var statusCode = response.statusCode;
var res = response;
@ -89,6 +96,14 @@ module.exports = function (url, opts, cb) {
if (opts.timeout) {
timeout(req, opts.timeout);
}
if (!body) {
req.end();
return;
}
req.write(body);
req.end();
};
get(url, opts, cb);

6
readme.md

@ -57,6 +57,12 @@ Default: `'utf8'`
Encoding to be used on `setEncoding` of the response data. If null, the body is returned as a Buffer.
##### options.body
Type: `string`, `Buffer`
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`.
##### options.timeout
Type: `number`

35
test.js

@ -1,6 +1,10 @@
/* global describe, it, before, after */
'use strict';
var assert = require('assert');
var got = require('./');
var http = require('http');
it('should do HTTP request', function (done) {
got('http://google.com', function (err, data) {
@ -99,3 +103,34 @@ it('should support timeout option', function (done) {
done();
});
});
describe('with POST ', function () {
var server;
before(function (done) {
server = http.createServer(function (req, res) {
req.pipe(res);
});
server.listen(8081, done);
});
after(function (done) {
server.close(done);
});
it('should support string as body option', function (done) {
got('http://0.0.0.0:8081', { body: 'string' }, function (err, data) {
assert.ifError(err);
assert.equal(data, 'string');
done();
});
});
it('should support Buffer as body option', function (done) {
got('http://0.0.0.0:8081', { body: new Buffer('string') }, function (err, data) {
assert.ifError(err);
assert.equal(data, 'string');
done();
});
});
});

Loading…
Cancel
Save