Last active
February 1, 2016 07:22
-
-
Save jcarroyo/874f8f3d1c84c688ab95 to your computer and use it in GitHub Desktop.
Pure http Node.js to call a remote REST API.
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'); | |
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