diff --git a/index.js b/index.js index 0fcc05c..c5a359c 100644 --- a/index.js +++ b/index.js @@ -242,7 +242,10 @@ function normalizeArguments(url, opts) { opts.method = opts.method || 'POST'; - if (isPlainObj(body)) { + 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)) { opts.headers['content-type'] = opts.headers['content-type'] || 'application/x-www-form-urlencoded'; body = opts.body = querystring.stringify(body); } diff --git a/package.json b/package.json index 117edde..8e1bdf8 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ "devDependencies": { "ava": "^0.16.0", "coveralls": "^2.11.4", + "form-data": "^1.0.1", "get-port": "^2.0.0", "get-stream": "^2.3.0", "into-stream": "^2.0.0", diff --git a/readme.md b/readme.md index 6b87a86..e59281a 100644 --- a/readme.md +++ b/readme.md @@ -244,7 +244,6 @@ const form = new FormData(); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); got.post('google.com', { - headers: form.getHeaders(), body: form }); ``` diff --git a/test/headers.js b/test/headers.js index 808f4b7..eb62f94 100644 --- a/test/headers.js +++ b/test/headers.js @@ -1,4 +1,5 @@ import test from 'ava'; +import FormData from 'form-data'; import got from '../'; import pkg from '../package.json'; import {createServer} from './helpers/server'; @@ -65,6 +66,29 @@ test('zero content-length', async t => { t.is(headers['content-length'], '0'); }); +test('form-data manual content-type', async t => { + const form = new FormData(); + form.append('a', 'b'); + const headers = (await got(s.url, { + headers: { + 'content-type': 'custom' + }, + body: form, + json: true + })).body; + t.is(headers['content-type'], 'custom'); +}); + +test('form-data automatic content-type', async t => { + const form = new FormData(); + form.append('a', 'b'); + const headers = (await got(s.url, { + body: form, + json: true + })).body; + t.is(headers['content-type'], `multipart/form-data; boundary=${form.getBoundary()}`); +}); + test.after('cleanup', async () => { await s.close(); });