NodeJS从请求函数内部返回数据请求模块

时间:2018-03-14 17:21:21

标签: node.js cookies request

我正在尝试使用nodejs中的请求模块发布帖子请求。请求发出后,我想从响应中返回cookie。由于某种原因,代码末尾的console.log打印未定义但是如果我控制日志" cookiestring"它在请求函数内部工作。我发现在cookies之前打印了undefined,这让我觉得在设置cookiestring之前会发生返回的cookiestring。如何确定在设置后返回cookiestring?

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())

0 个答案:

没有答案