Daniel Tonon
Daniel Tonon

Reputation: 10472

How to dynamically read external json files in node.js?

I am creating a website that reads externally hosted json files and then uses node.js to populate the sites content.

Just to demonstrate what I'm after, this is a really simplified version of what I'm trying to do in node.js

var ids = [111, 222, 333];

ids.forEach(function(id){
    var json = getJSONsomehow('http://www.website.com/'+id+'.json');

    buildPageContent(json);
});

Is what I want to do possible?

(Marked as a duplicate of "How do I return the response from an asynchronous call?" see my comment below for my rebuttal)

Upvotes: 3

Views: 3385

Answers (2)

rsp
rsp

Reputation: 111424

You are trying to get it synchronously. What you should aim for instead, is not a function used like this:

var json = getJSONsomehow('http://www.website.com/'+id+'.json');

but more like this:

getJSONsomehow('http://www.website.com/'+id+'.json', function (err, json) {
  if (err) {
    // error
  } else {
    // your json can be used here
  }
});

or like this:

getJSONsomehow('http://www.website.com/'+id+'.json')
  .then(function (json) {
    // you can use your json here
  })
  .catch(function (err) {
    // error
  });

You can use the request module to get your data with something like this:

var request = require('request');
var url = 'http://www.website.com/'+id+'.json';

request.get({url: url, json: true}, (err, res, data) => {
  if (err) {
    // handle error
  } else if (res.statusCode === 200) {
    // you can use data here - already parsed as json
  } else {
    // response other than 200 OK
  }
});

For a working example see this answer.

For more info see: https://www.npmjs.com/package/request

Upvotes: 4

Sabik
Sabik

Reputation: 1679

I think problem is in async request. Function will return result before request finished.

AJAX_req.open( "GET", url, true );

Third parameter specified async request.

You should add handler and do all you want after request finished.

For example:

function AJAX_JSON_Req( url ) {
    var AJAX_req = new XMLHttpRequest.XMLHttpRequest();
    AJAX_req.open( "GET", url, true );
    AJAX_req.setRequestHeader("Content-type", "application/json");

    AJAX_req.onreadystatechange = function() {
        if (AJAX_req.readyState == 4 && AJAX_req.status == 200) {
            console.log(AJAX_req.responseText);
        }
    };
}

Upvotes: 0

Related Questions