如何从 cookie jar 记录 cookie?

Ogd*_*den 2 node.js request-promise

如何使用 request-promise npm 模块记录存储在 cookie jar 中的 cookie。

我曾尝试打印 cookie jar 变量,但正如预期的那样不起作用。

我是如何创建罐子的,

var request = require('request-promise');
var sess = request.jar()
Run Code Online (Sandbox Code Playgroud)

发送请求的代码,

request({url: myurl, jar: sess}, function () {
    request(
        {
            url: 'myurl',
            method: 'POST',
            headers: [
            {
                "Accept": "application/json",
            }
            ],
            postData: {
                "xqr":"1"
            }
        }
)
Run Code Online (Sandbox Code Playgroud)

我希望所有用于发送我的请求的 cookie 都使用 console.log()

Ahm*_*ven 5

request 在内部使用了强硬的 cookie。所以你可以很容易地访问到tough-cookie store,它是一个抽象类并使用它的原型函数getAllCookies

function logCookies(jar){
    jar._jar.store.getAllCookies(function(err, cookieArray) {
        if(err) throw new Error("Failed to get cookies");
        console.log(JSON.stringify(cookieArray, null, 4));
    });
}
Run Code Online (Sandbox Code Playgroud)

这将记录所有 cookie 及其属性。

[
    {
        "key": "1P_JAR",
        "value": "1P_JAR_VALUE",
        "expires": "2019-01-23T20:09:38.000Z",
        "domain": "google.com",
        "path": "/",
        "hostOnly": false,
        "creation": "2018-12-24T20:09:37.800Z",
        "lastAccessed": "2018-12-24T20:09:38.097Z"
    },
    {
        "key": "NID",
        "value": "NID_VALUE",
        "expires": "2019-06-25T20:09:38.000Z",
        "domain": "google.com",
        "path": "/",
        "httpOnly": true,
        "hostOnly": false,
        "creation": "2018-12-24T20:09:37.802Z",
        "lastAccessed": "2018-12-24T20:09:38.098Z"
    }
]
Run Code Online (Sandbox Code Playgroud)

如果您只想获取原始 cookie 字符串,您可以简单地使用

console.log(cookieArray.map(cookie => cookie.toString()))
Run Code Online (Sandbox Code Playgroud)

它会给你

[
    '1P_JAR=1P_JAR_VALUE; Expires=Wed, 23 Jan 2019 20:15:02 GMT; Domain=google.com; Path=/',
    'NID=NID_VALUE; Expires=Tue, 25 Jun 2019 20:15:02 GMT; Domain=google.com; Path=/; HttpOnly'
]
Run Code Online (Sandbox Code Playgroud)