Browse Source

Detect formdata body and set content-type header (#220)

node-7
Dylan Piercey 9 years ago
committed by Sindre Sorhus
parent
commit
57f13d9af2
  1. 5
      index.js
  2. 1
      package.json
  3. 1
      readme.md
  4. 24
      test/headers.js

5
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);
}

1
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",

1
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
});
```

24
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();
});

Loading…
Cancel
Save