user1547174 user1547174 - 4 years ago 137
Javascript Question

Multiple node.js requests

My controller is using the

request
package to make server-side HTTP requests to another API. My question is how can I make MULTIPLE of these requests? Here is my current code:

** UPDATED CODE **

module.exports = function (req, res) {
var context = {};
request('http://localhost:3000/api/single_project/' + req.params.id, function (err, resp1, body) {
context.first = JSON.parse(body);
request('http://localhost:3001/api/reports/' + req.params.id, function (err, resp2, body2) {
context.second = JSON.parse(body2); //this line throws 'SyntaxError: Unexpected token u' error
res.render('../views/project', context);
});
});


};

I need to make two more of those calls and send the data returned from it to my template...

Can someone help?

Thanks in advance!

Answer Source

Simple solution

Nest request calls. This is how you can handle the dependency between requests. Just make sure your parameters are unique across scopes if needed.

module.exports = function (req, res) {
    var context = {};
    request('http://localhost:3000/api/1st', function (err, resp1, body) {
        var context.first = JSON.parse(body);
        request('http://localhost:3000/api/2nd', function (err, resp2, body) {
            context.second = JSON.parse(body);
            request('http://localhost:3000/api/3rd', function (err, resp3, body) {
                context.third = JSON.parse(body);
                res.render('../views/project', context);
            });
        });
    });
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download