Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js multiple http requests

I am a newbie to node and js and try to create a website in express that makes three Rest API calls before rendering the page. At the moment I have the below, which returns some json which I convert into a list of objects.

Some of these properties only return id values and I would like to run three more API requests that return lookups on these Id's so that I can present this data to the user as meaningful values.

I could do this synchronously by running the next API call where I am currently rendering the index page, but that looks really messy. All the async tutorials I have seen confuse the hell out of my newbie way of thinking though. Can someone post an easy to follow example for async that somewhat reflects the below structure?

var issues_json = "";
var request = http.request(options, function(response) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);

    response.on("data", function(data) {
        issues_json += data;
    });

    response.on("end", function() {
        console.log(issues_json);
        var column_obj = JSON.parse(issues_json);
        res.render('index', {
            title: 'List of Issues',
            response: issues_json,
            objects: column_obj
        });
    });

    response.on("error", function(e) {
        console.log(e.Message);
        res.render('index', {
            title: 'error',
            e: e.Message
        });
    });
});
request.end();
like image 446
Hans Avatar asked Aug 20 '12 22:08

Hans


1 Answers

You should use Request

You would have something like

app.get("/route", function(req, res) {

  var callbackThree = function(error, resp, body) {
    var data = JSON.parse(body);
    res.send({title; "My Title", data: data});
  }

  var callbackTwo = function(error, resp, body) {
    request("api.com/42", callBackThree);
  }

  var callbackOne = function(error, resp, body) {
    request("api.com/things", callBackTwo);
  }

  request("api.com/users", callBackOne);
}
like image 137
3on Avatar answered Oct 21 '22 06:10

3on