Skip to content

Instantly share code, notes, and snippets.

@mcfedr
Last active April 14, 2016 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcfedr/0a6fbaeaf0cfaddbeadfe145c002c8e5 to your computer and use it in GitHub Desktop.
Save mcfedr/0a6fbaeaf0cfaddbeadfe145c002c8e5 to your computer and use it in GitHub Desktop.
Shows how the content-length can be unknown
'use strict';
const FormData = require('form-data'),
fetch = require('node-fetch');
Promise.all([
fetch('http://httpbin.org/stream/10'),
fetch('http://httpbin.org/stream/10')
]).then(res => {
let data = new FormData();
// I have put 2 streams to show that I need FormData and its multipart support
data.append('a', res[0].body);
data.append('b', res[1].body);
data.append('c', 'something else');
// In this version the an incorrect content-length header is set because `form-data` skips over the streams
// In this case the server will not see the data
// Removing getLengthSync prevents content-length from being set and the server sees the data correctly
data.getLengthSync = null;
return fetch('http://httpbin.org/post', {
method: 'POST',
body: data
})
.then(res => res.text())
.then(text => {
console.log(text);
});
})
.catch(err => {
console.error(err);
});
'use strict';
const FormData = require('form-data'),
fetch = require('node-fetch'),
http = require('http');
http.request('http://httpbin.org/stream/10', (res) => {
let data = new FormData();
data.append('a', res);
data.append('c', 'something else');
// In this version the error is thrown because `form-data` correctly finds that it cannot
// find the length of the stream
// Removing getLengthSync prevents content-length from being set and the server sees the data correctly
data.getLengthSync = null;
return fetch('http://httpbin.org/post', {
method: 'POST',
body: data
})
.then(res => res.text())
.then(text => {
console.log(text);
})
.catch(err => {
console.error(err);
});
}).end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment