Created
January 13, 2016 06:36
-
-
Save kaidokert/d48b06671eb21721c029 to your computer and use it in GitHub Desktop.
Easily make Node http requests with built in http and Promises module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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