The Node.JS HTTP and HTTPS modules only provide .get
shortcut function, unlike AngularJS's $http
which provides them all. I went about creating a function
that returns one of these shortcut function
s:
'use strict';
var http = require('http');
function httpF(method) {
return function (options, body_or_cb, cb) {
if (!cb) {
cb = body_or_cb;
body_or_cb = null;
}
options['method'] = method;
if (body_or_cb)
if (!options)
options = {'headers': {'Content-Length': Buffer.byteLength(body_or_cb)}};
else if (!options.headers)
options.headers = {'Content-Length': Buffer.byteLength(body_or_cb)};
else if (!options.headers['Content-Length'])
options.headers['Content-Length'] = Buffer.byteLength(body_or_cb);
var req = http.request(options, function (res) {
if (!res)
return cb(res);
else if ((res.statusCode / 100 | 0) > 3)
return cb(res);
return cb(null, res);
});
body_or_cb && req.write(body_or_cb);
req.end();
return req;
};
}
It pushes the callback through an (err, res)
signature also. The idea here is to enable chaining in async.js or use as a Bluebird promise.
Usage:
var httpPOST = httpF('POST');
httpPOST({
protocol: 'http:',
host: 'httpbin.org',
path: '/post',
headers: {'Content-Type': 'application/json'}
}, JSON.stringify({hello: 'world'}), function (err, res) {
if (err)
console.error(err.statusCode, err.statusMessage);
else
console.info(res.statusCode, res.statusMessage);
});
Some improvement ideas:
- Use
url.parse
to enablehttpPOST('https://httpbin.org/post', ..
(including use ofhttps
module) - Wrap all errors up into something
util.inherits
fromError
- Fix bug that stops
async.series
from continuing after failure (even happens with this hacke ? cb() : cb(null, r)
)
I also submitted this as a PR, but it was rejected (as expected).