Skip to content

Instantly share code, notes, and snippets.

@saich
Forked from wilsonpage/reqUrl.js
Created December 6, 2011 13:42
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 saich/1438245 to your computer and use it in GitHub Desktop.
Save saich/1438245 to your computer and use it in GitHub Desktop.
A wrapper module for 'http.request' function...
// Based upon https://gist.github.com/1393666
var querystring = require('querystring'),
url = require('url'),
http = require('http');
/**
* @param {string} reqUrl The complete URL to send the request to
* @param {Object} options options of the request
* @param {Function} cb Callback function that is to be called with response / errors
*
* Options: Can contain following keys:
* - method (The HTTP method as string)
* - headers (Array of request headers)
* - params (Object of params to be sent along with the request)
* - format (The format in which the params has to be sent. Valid values: json | form. Defaults to form)
*
* Callback format: <code>function(body, error, response) {}</code>
* - body: String. Content of the response.
* - error: Errors occured in the connection / request
* - response: The complete response object
*
* The caller should check for error parameter first. If an error occured,
* both body and response will be <code>null</code>
*/
exports.send = function(reqUrl, options, cb){
if(typeof options === "function"){ cb = options; options = {}; }// incase no options passed in
// parse url to chunks
reqUrl = url.parse(reqUrl);
// http.request settings
var settings = {
host: reqUrl.hostname,
port: reqUrl.port || 80,
path: reqUrl.pathname,
headers: options.headers || {},
method: options.method || 'GET'
};
// if there are params:
if(options.params){
var format = options.format || 'form';
if(format == 'json') {
options.params = JSON.stringify(options.params);
settings.headers['Content-Type'] = 'application/json';
} else {
options.params = querystring.stringify(options.params);
settings.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
settings.headers['Content-Length'] = options.params.length;
};
// MAKE THE REQUEST
var req = http.request(settings);
// if there are params: write them to the request
if(options.params){ req.write(options.params) };
// when the response comes back
req.on('response', function(res){
res.body = '';
res.setEncoding('utf-8');
// concat chunks
res.on('data', function(chunk){ res.body += chunk });
// when the response has finished
res.on('end', function(){
// fire callback
cb(res.body, null, res);
});
});
req.on('error', function(exception){
cb(null, exception, null);
});
// end the request
req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment