Browse Source

allow non-plain object as request body (#217)

* allow non-plain object as request body

* add tests for object request body

* fix test for non-plain object request body

* fix tests to pass linter
v5.x
bisubus 9 years ago
committed by Vsevolod Strukchinsky
parent
commit
3709fe95d2
  1. 5
      index.js
  2. 1
      package.json
  3. 31
      test/post.js

5
index.js

@ -18,7 +18,6 @@ var PinkiePromise = require('pinkie-promise');
var unzipResponse = require('unzip-response');
var createErrorClass = require('create-error-class');
var nodeStatusCodes = require('node-status-codes');
var isPlainObj = require('is-plain-obj');
var parseJson = require('parse-json');
var isRetryAllowed = require('is-retry-allowed');
var pkg = require('./package.json');
@ -253,7 +252,7 @@ function normalizeArguments(url, opts) {
var body = opts.body;
if (body) {
if (typeof body !== 'string' && !Buffer.isBuffer(body) && !isStream(body) && !isPlainObj(body)) {
if (typeof body !== 'string' && !(body !== null && typeof body === 'object')) {
throw new Error('options.body must be a ReadableStream, string, Buffer or plain Object');
}
@ -262,7 +261,7 @@ function normalizeArguments(url, opts) {
if (isStream(body) && typeof body.getBoundary === 'function') {
// Special case for https://github.com/form-data/form-data
opts.headers['content-type'] = opts.headers['content-type'] || 'multipart/form-data; boundary=' + body.getBoundary();
} else if (isPlainObj(body)) {
} else if (body !== null && typeof body === 'object' && !Buffer.isBuffer(body) && !isStream(body)) {
opts.headers['content-type'] = opts.headers['content-type'] || 'application/x-www-form-urlencoded';
body = opts.body = querystring.stringify(body);
}

1
package.json

@ -47,7 +47,6 @@
"dependencies": {
"create-error-class": "^3.0.1",
"duplexer2": "^0.1.4",
"is-plain-obj": "^1.0.0",
"is-redirect": "^1.0.0",
"is-retry-allowed": "^1.0.0",
"is-stream": "^1.0.0",

31
test/post.js

@ -32,6 +32,23 @@ test('GET can have body', async t => {
t.is(headers.method, 'GET');
});
test('sends null-prototype objects', async t => {
const {body} = await got(s.url, {body: Object.create(null)});
t.is(body, '');
});
test('sends plain objects', async t => {
const {body} = await got(s.url, {body: {}});
t.is(body, '');
});
test('sends non-plain objects', async t => {
class Obj {}
const {body} = await got(s.url, {body: new Obj()});
t.is(body, '');
});
test('sends strings', async t => {
const {body} = await got(s.url, {body: 'wow'});
t.is(body, 'wow');
@ -90,11 +107,17 @@ test('content-length header disabled for chunked transfer-encoding', async t =>
});
test('object in options.body treated as querystring', async t => {
const {body} = await got(s.url, {
body: {
such: 'wow'
class Obj {
constructor() {
this.such = 'wow';
}
});
get ouch() {
return 'yay';
}
}
const {body} = await got(s.url, {body: new Obj()});
t.is(body, 'such=wow');
});

Loading…
Cancel
Save