node.js multiple http requests
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);
}
Hans
Updated on July 15, 2022Comments
-
Hans almost 2 years
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();
-
Hans over 11 yearsThanks 3on I understand that I can use callbacks but wonder if using an async approach would be better. I need to make 4 requests in total and would prefer to kick them off and then have something like an 'on completion of all' event that maps the lookups and renders the page. This may just be me misunderstanding async.
-
3on over 11 yearsThis is purely async. Nothing is blocking here. Using events or callbacks is just two ways to handle async.
-
Mahtab Alam almost 7 yearsThanks @3on that helped