request-promise 模拟登录以后,怎么拿到 set-cookie

request 可以这样:

request.post({url: 'http://127.0.0.1:3000/users/login', form: {user: 'admin'}}, function (err, res, body) {
  console.log(res.headers['set-cookie']);
}); 

但是 request-promise 只返回 body 一个参数。
此外,request.post 方法不能被 bluebird.promisify。

最终目的是得到一个能放在 async/await 里面的方法,如:

async function getCookie(req, res, next) {
    let cookie = await request(...);
    return ...;
}

三种方法

一、async 立即执行函数

function test() {
  return new Promise((resolve, reject) => {
      request(url, function() {
        resolve(cookie);
      });
    }).on('error', (error) => {
      reject(error);
    });
  });
};

(async () => {
  try {
    console.log(await test());
  } catch (error) {
    console.log(error);
  }
})();

二、和上一个方法一样,new 一个 Promise 后 return

const post = function (url, body, headers) {
    return new Promise((resolve, reject) => {
        let data = { url : url, body : body };
        if (headers) data.headers = headers;
        request.post(data, function (error, response, body) {
            if (error)  return reject(error);
            // 如果结果只需要cookie话,body可以不用返回
            resolve({ body : body, cookie : response.headers['set-cookie'] });
        });
    });
};

// 调用
let {body, cookie} = await post('url', body);

三、request-promise 有个 transform

const request = require('request')
const requestPromise = require('request-promise')

const reqOpt = { url : url, qs : req.query, json: req.body };
const reqPromiseOpt = Object.assign({}, reqOpt, {transform: function (body, res, resolveWithFullResponse) {
  return res['headers']['set-cookie'] 
}})

function getCookieByRequest() {
  return new Promise(function (resolve, reject) {
    request.post(reqOpt, function (err, res, body) {
      if (err) {
        reject(err)
        return
      }

      if (res && res['headers']) {
        resolve(res['headers']['set-cookie'])
      }
    })
  })
}

function getCookieByRequestPromise() {
  return requestPromise.post(reqPromiseOpt)
}

async function test() {
  const cookie = await getCookieByRequest()
  const cookie2 = await getCookieByRequestPromise()
  
  console.log(cookie, cookie2)
}

你可能感兴趣的:(request-promise 模拟登录以后,怎么拿到 set-cookie)