From 2c8ee3fc913ed6f3ce9a70cc2c1a9db736356449 Mon Sep 17 00:00:00 2001 From: Vsevolod Strukchinsky Date: Mon, 1 Dec 2014 16:36:38 +0700 Subject: [PATCH] Close #15 PR: Implement body option. --- index.js | 17 ++++++++++++++++- readme.md | 6 ++++++ test.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index ad3ec63..ff10c37 100644 --- a/index.js +++ b/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); diff --git a/readme.md b/readme.md index 8680da6..c5b1f89 100644 --- a/readme.md +++ b/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` diff --git a/test.js b/test.js index a72f45b..99d6ff6 100644 --- a/test.js +++ b/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(); + }); + }); +});