Skip to content

Instantly share code, notes, and snippets.

@hernan
Forked from wilsonpage/reqUrl.js
Created November 20, 2012 21:20
Show Gist options
  • Save hernan/4121225 to your computer and use it in GitHub Desktop.
Save hernan/4121225 to your computer and use it in GitHub Desktop.
A function I made that wraps the node http.request function to make it a little more friendly. In my case I am using it for API route testing.
// module dependencies
var http = require('http'),
url = require('url');
/**
* UrlReq - Wraps the http.request function making it nice for unit testing APIs.
*
* @param {string} reqUrl The required url in any form
* @param {object} options An options object (this is optional)
* @param {Function} cb This is passed the 'res' object from your request
*
*/
exports.urlReq = 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){
options.params = JSON.stringify(options.params);
settings.headers['Content-Type'] = 'application/json';
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, res);
});
});
// end the request
req.end();
}
// Simple Example (defaults to GET)
mylib.urlReq('http://mysite.local:82/newUser', function(body, res){
// do your stuff
});
// More complex Example 2
mylib.urlReq('http://mysite.local:82/newUser', {
method: 'POST',
params:{
name: 'Tester',
email: 'Tester@example.com',
password: 'password'
}
}, function(body, res){
// do your stuff
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment