I am trying to make a post request using the request module in nodejs. After the request is made I would like to return the cookies from the response. For some reason the console.log at the end of the code prints undefined but if I console log "cookiestring" inside of the request function it works. I see that undefined is printed before the cookies which makes me think that return cookiestring happens before cookiestring has been set. How can I make sure cookiestring is returned after it has been set?
const request = require('request');
var Cookie = require('request-cookies').Cookie;
function getbmdata(){
var bmheaders = {
'Host': 'www.adidas.ch',
'Connection': 'keep-alive',
'Content-Length': '1861',
'Origin': 'https://www.adidas.ch',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36',
'Content-type': 'application/json',
'Accept': '*/*',
'Referer': 'https://www.adidas.ch/en/superstar-foundation-shoes/AF5666.html',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8'
}
var bmreq = {
'uri':'https://www.adidas.ch/_bm/_data',
'method':'POST',
'json': true,
'headers': bmheaders,
'proxy':'http://localhost.charlesproxy.com:8888',
'rejectUnauthorized': false }
var cookiestring = "";
request( bmreq, (err, res, body) => {
if (err) { return console.log(err); }
var rawcookies = res.headers['set-cookie'];
for (var i in rawcookies) {
var cookie = new Cookie(rawcookies[i]);
cookiestring += cookie.key+"="+ cookie.value+";";
};
return cookiestring
});
}
console.log( getbmdata())