Skip to content

Instantly share code, notes, and snippets.

@kaidokert
Created January 13, 2016 06:36
Show Gist options
  • Save kaidokert/d48b06671eb21721c029 to your computer and use it in GitHub Desktop.
Save kaidokert/d48b06671eb21721c029 to your computer and use it in GitHub Desktop.
Easily make Node http requests with built in http and Promises module
var http = require('http');
function make_request(options, payload) {
return new Promise(function(resolve,reject) {
if(payload) options.method = 'POST'; else options.method = 'GET';
var request = http.request(options,function(response) {
var str = '';
response.on('error', function() { reject('Error'); } )
response.on('data', function (chunk) { str += chunk; })
response.on('end', function () { resolve(JSON.parse(str));})
});
if(payload) {
request.setHeader('Content-Type','application/json');
request.write(JSON.stringify(payload));
}
request.end();
});
}
resource = {
host : 'jsonplaceholder.typicode.com',
path : '/posts'
}
make_request(resource,{ userId : 1, title : 'wut?'} ).then(function(postreply) {
console.log(postreply);
make_request( resource ).then(function(getreply) {
console.log(getreply);
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment