0

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())
K Kreid
  • 83
  • 8
  • Welcome to asynchronous development in Javascript. This is a common learning stumbling block with node.js. `request()` is asynchronous. That means it calls it's callback some time in the future AFTER your function has returned. Thus, you cannot return its value directly from your function. See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 for how to communicate back the value either via a callback or via a promise. – jfriend00 Mar 14 '18 at 17:25
  • @jfriend00 I thought that it had something with it not being asynchronous. I see what it needs to be doing but I cant get it running with my code. Ive tried using the callback method but without success – K Kreid Mar 14 '18 at 17:36
  • I'd suggest using the `request-promise()` library. It returns a promise for you that you can just use directly. If you get stuck trying to make that work, then write a new question with the code you have attempted and explain what does and doesn't work and exactly what, in that code, you need help with. – jfriend00 Mar 14 '18 at 17:41

0 Answers0