get json response from utl and manipulate the data in node js code example

Example 1: nodejs store json from web api

// NodeJS
const http = require("http");
var url = 'https://example.com/file.json'; // Request URL

http.get(url, function(res){
    var body = '';

    res.on('data', function(chunk){
        body += chunk;
    });

    res.on('end', function(){
        var data = JSON.parse(body); 
        console.log("Got a response: ", data.value);
    });
}).on('error', function(e){
      console.log("Got an error: ", e);
});

Example 2: node js fetch data from url

var http = require('http');

var options = {
    host: 'google.com',
    path: '/'
}
var request = http.request(options, function (res) {
    var data = '';
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on('end', function () {
        console.log(data);

    });
});
request.on('error', function (e) {
    console.log(e.message);
});
request.end();

Tags: