Skip to content

Instantly share code, notes, and snippets.

@Eitz

Eitz/node-simple-http.js

Forked from wilsonpage/reqUrl.js
Last active Aug 23, 2016
Embed
What would you like to do?
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
const http = require('http');
const url = require('url');
/**
* request - 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
*
*/
var _request = function(reqUrl, options, cb){
// incase no options passed in
if (typeof options === "function") {
cb = options; options = {};
}
// 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
const 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', res => {
res.body = '';
res.setEncoding('utf-8');
// concat chunks
res.on('data', chunk => { res.body += chunk });
// when the response has finished
res.on('end', () => {
// fire callback
cb(res.body, res);
});
});
// end the request
req.end();
};
// exporting the function
module.exports = {
request: _request
};
/*
// Simple example (defaults to GET)
const simpleHttp = require('./node-simple-http');
var simpleHttp.request('http://mysite.local:82/new-user', (body, res) => {
// do your stuff
});
// More complex example 2
simpleHttp.request('http://mysite.local:82/new-user', {
method: 'POST',
params:{
name: 'Tester',
email: 'tester@example.com',
password: '****'
}
}, (body, res) => {
// do your stuff
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.