Ad

Node.js - Multiple Requests With Cookies

- 1 answer

I am building an app using Node.js. I am using the request package to make server-side GET requests. Specifically, I am making requests that use custom HTTP headers:

https://www.npmjs.com/package/request#custom-http-headers

The documentation shows how to make one request at a time. However, I need to make a request to two different API's. Does anyone have any idea how to do this? My current code for making one request:

var cookie = parseCookie.parseCookie(req.headers.cookie);
var cookieText = 'sid='+cookie;
var context;

function callback(error, response, body) {

    var users = JSON.parse(body);
    res.render('../views/users', {
        context: users
    });
}

var options = {
    url: 'http://localhost:3000/api/admin/users/',
    headers: {
        host: 'localhost:3000',
        connection: 'close',
        cookie: cookieText
    }
};

request(options, callback);
//need to make a request to another API.

As a side note, the reason I need to use custom HTTP headers is so I can include a cookie so my API can authenticate.

Ad

Answer

For flow control in nodejs, I would recommend you to use async

If you want to do in parallel without order of execution :

async.parallel([
      function(callback) { request(apiCall1Options, callback); },

      function(callback) { request(apiCall2Options, callback); }

  ], function(err, apiCallResults) { console.log(apiCallResults) })

If you need order, use async.waterfall.

Could be done as well by simply using plain callbacks, which I wouldnt recommend you using, or a promise library, like Q, or bluebird.

Ad
source: stackoverflow.com
Ad