Skip to content

Instantly share code, notes, and snippets.

@jcarroyo
Last active February 1, 2016 07:22
Show Gist options
  • Save jcarroyo/874f8f3d1c84c688ab95 to your computer and use it in GitHub Desktop.
Save jcarroyo/874f8f3d1c84c688ab95 to your computer and use it in GitHub Desktop.
Pure http Node.js to call a remote REST API.
var http = require('http');
var url = require('url');
var urlAPI = "http://jsonplaceholder.typicode.com/comments";
var urlParts = url.parse(urlAPI);
var options = {
protocol: urlParts.protocol,
hostname: urlParts.host,
port: urlParts.port || 80,
method: 'GET',
path: urlParts.path
};
var req = http.request(options, function(res){
var data = "";
res.on('data', function(d){
data += d;
})
res.on('end', function(){
var comments = null;
try{
comments = JSON.parse(data);
}catch(err){
console.log("Cannot convert to JSON");
}
if(comments){
console.log("Total comments " + comments.length);
console.log("First comment");
console.log(comments[0]);
}
})
})
req.on('error', function(err){
console.log(err);
})
req.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment