request-promise 发送带 cookie 的请求

npm 上面的写法,使用了 tough-cookie 模块:

let tough = require('tough-cookie');
 
// Easy creation of the cookie - see tough-cookie docs for details
let cookie = new tough.Cookie({
    key: "some_key",
    value: "some_value",
    domain: 'api.mydomain.com',
    httpOnly: true,
    maxAge: 31536000
});
 
// Put cookie in an jar which can be used across multiple requests
let cookiejar = rp.jar();
cookiejar.setCookie(cookie, 'https://api.mydomain.com');
// ...all requests to https://api.mydomain.com will include the cookie
 
let options = {
    uri: 'https://api.mydomain.com/...',
    jar: cookiejar // Tells rp to include cookies in jar that match uri
};
 
rp(options)
    .then(function (body) {
        // Request succeeded...
    })
    .catch(function (err) {
        // Request failed...
    });

还有一种写法,是 github 的 issue 上看的

这种写法不需要 tough-cookie 模块,把使用 tough-cookie 模块的步骤改成 rp.cookie('' + cookie) 即可,即先把 cookie 转化成字符串,如这样的形式:

'connect.sid=s%3AWWUQ9f5g4HnqxC02B7qwKO_Rx9nDbubu.1GZuzQ4rQCE8NZQVaK74ogwURgC83b5gKm7FQrVT%2F2Q; Path=/; HttpOnly'

然后传给 rp.cookie()

let cookies = res.headers['set-cookie'];
console.log(cookies);

let cookie_1 = rp.cookie('' + cookies[1]);
console.log(cookie_1);

let cookie_0 = rp.cookie('' + cookies[0]);
console.log(cookie_0);

let cookiejar = rp.jar();
cookiejar.setCookie(cookie_1, url);
cookiejar.setCookie(cookie_0, url);

let options = {
  uri: url,
  method: 'GET',
  jar: cookiejar
};

rp(options).then(function (body) {
  console.log(body);
})

request 模块也类似

你可能感兴趣的:(request-promise 发送带 cookie 的请求)