javascript - Http get multiple json files from different API endpoints using node express -
i'm looking efficient way multiple json files different api endpoints using node.
basically i'd store each json object in variable, , send them jade template files parsing. i've got setup working getting one single json file (jsonfile1) doing following:
httpoptions = { host: 'api.test123.com', path : '/content/food/?api_key=1231241412', headers: { "accept": "application/json", 'content-type': 'application/json' }, method: "get", port: 80 } var jsonfile1; http.get(httpoptions, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { jsonfile1= json.parse(body) console.log("got response: " + jsonfile1); }); }).on('error', function(e) { console.log("got error: " + e.message); }); app.set('views', __dirname); app.get('/', function(req, res) { res.render('home', { data: jsonfile1 }); });
but don't want have repeat of multiple json endpoints , send them home jade template.
any ideas efficiently?
based on code, quick example using excellent async library.
var async = require('async'), // array of apis httpoptions = [ { host: 'api.test123.com', path : '/content/food/?api_key=1231241412', headers: { "accept": "application/json", 'content-type': 'application/json' }, method: "get", port: 80 }, host: 'api.test234.com', path : '/content/food/?api_key=1231241412', headers: { "accept": "application/json", 'content-type': 'application/json' }, method: "get", port: 80 } ]; // put logic fetching data in own function function getfile(options, done) { http.get(options, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { done(null, json.parse(body)); console.log("got response: " + jsonfile1); }); }).on('error', function(e) { done(e); console.log("got error: " + e.message); }); } app.get('/', function(req, res) { // map options through getfile function, resulting in array of each response async.map(httpoptions, getfile, function (err, jsonfiles) { // should check errors here res.render('home', { data: jsonfiles }); }); });