FormData support with form-data

This commit is contained in:
AJ ONeal 2018-07-06 19:38:47 -06:00
parent d5af2ae5fe
commit 8758964610
4 changed files with 91 additions and 5 deletions

30
examples/form-data.js Normal file
View File

@ -0,0 +1,30 @@
'use strict';
//var request = require('@coolaj86/urequest');
// To check and make sure the outputs are the same
//var request = require('request');
var request = require('../');
// will redirect to https://www.github.com and then https://github.com
//request('http://www.github.com', function (error, response, body) {
request(
//{ url: 'http://postb.in/syfxxnko'
{ url: 'http://localhost:3007/form-data/'
, headers: {
'X-Foo': 'Bar'
}
, formData: {
foo: 'bar'
, baz: require('fs').createReadStream(require('path').join(__dirname, 'get-to-json.js'))
}
}
, function (error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
return;
}
console.log('statusCode:', response.statusCode); // The final statusCode
console.log('Final href:', response.request.uri.href); // The final URI
console.log('Body Length:', body.length); // body length
}
);

View File

@ -150,6 +150,10 @@ function setDefaults(defs) {
var req; var req;
var finalOpts = {}; var finalOpts = {};
var _body; var _body;
var MyFormData;
var form;
var formHeaders;
var requester;
if (opts.body) { if (opts.body) {
if (true === opts.json) { if (true === opts.json) {
@ -174,26 +178,62 @@ function setDefaults(defs) {
// chunked is generally only well-supported downstream // chunked is generally only well-supported downstream
//finalOpts.headers['Content-Length'] = _body.byteLength || _body.length; //finalOpts.headers['Content-Length'] = _body.byteLength || _body.length;
} }
if (opts.formData) {
try {
MyFormData = opts.FormData || require('form-data');
// potential options https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15
} catch(e) {
console.error("urequest does not include extra dependencies by default");
console.error("if you need to use 'form-data' you may install it, like so:");
console.error(" npm install --save form-data");
cb(e);
return;
}
try {
form = new MyFormData();
Object.keys(opts.formData).forEach(function (key) {
form.append(key, opts.formData[key]);
});
} catch(e) {
cb(e);
return;
}
formHeaders = form.getHeaders();
Object.keys(formHeaders).forEach(function (header) {
finalOpts.headers[header] = formHeaders[header];
});
}
// TODO support unix sockets // TODO support unix sockets
if ('https:' === finalOpts.protocol) { if ('https:' === finalOpts.protocol) {
// https://nodejs.org/api/https.html#https_https_request_options_callback // https://nodejs.org/api/https.html#https_https_request_options_callback
debug("\n[urequest] https.request(opts):"); debug("\n[urequest] https.request(opts):");
debug(finalOpts); debug(finalOpts);
req = https.request(finalOpts, onResponse); requester = https;
} else if ('http:' === finalOpts.protocol) { } else if ('http:' === finalOpts.protocol) {
// https://nodejs.org/api/http.html#http_http_request_options_callback // https://nodejs.org/api/http.html#http_http_request_options_callback
debug("\n[urequest] http.request(opts):"); debug("\n[urequest] http.request(opts):");
debug(finalOpts); debug(finalOpts);
req = http.request(finalOpts, onResponse); requester = http;
} else { } else {
cb(new Error("unknown protocol: '" + opts.uri.protocol + "'")); cb(new Error("unknown protocol: '" + opts.uri.protocol + "'"));
return; return;
} }
req.on('error', function (e) { if (form) {
cb(e); debug("\n[urequest] '" + finalOpts.method + "' (request) form");
}); debug(formHeaders);
// generally uploads don't use Chunked Encoding (some systems have issues with it)
// and I don't want to do the work to calculate the content-lengths. This seems to work.
form.submit(finalOpts, onResponse);
//req = requester.request(finalOpts, onResponse);
//req.on('error', cb);
//form.pipe(req);
return;
}
req = requester.request(finalOpts, onResponse);
req.on('error', cb);
if (_body) { if (_body) {
debug("\n[urequest] '" + finalOpts.method + "' (request) body"); debug("\n[urequest] '" + finalOpts.method + "' (request) body");
@ -320,6 +360,8 @@ module.exports._keys = Object.keys(_defaults).concat([
'encoding' 'encoding'
, 'body' , 'body'
, 'json' , 'json'
, 'formData'
, 'FormData'
]); ]);
module.exports.debug = (-1 !== (process.env.NODE_DEBUG||'').split(/\s+/g).indexOf('urequest')); module.exports.debug = (-1 !== (process.env.NODE_DEBUG||'').split(/\s+/g).indexOf('urequest'));

View File

@ -3,6 +3,9 @@
"version": "1.1.4", "version": "1.1.4",
"description": "A lightweight drop-in replacement for request", "description": "A lightweight drop-in replacement for request",
"main": "index.js", "main": "index.js",
"files": [
"lib"
],
"directories": { "directories": {
"example": "examples" "example": "examples"
}, },

11
tests/tcp-listener.js Normal file
View File

@ -0,0 +1,11 @@
'use strict';
var net = require('net');
var server = net.createServer(function (socket) {
socket.on('data', function (chunk) {
console.info(chunk.toString('utf8'));
});
})
server.listen(3007, function () {
console.info("Listening on", this.address());
});