Node.js - Multiple Requests With Cookies
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.
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM