NPM tough-cookie:保存一个cookie,然后转储它

npm tough-cookie: save a cookie and then dump it

本文关键字:cookie 一个 然后 转储 tough-cookie 保存 NPM      更新时间:2023-09-26

我想做一个非常简单的任务:

  1. 创建http request (npm install request)到http://google.com,保存cookie到cookiejar
  2. 查看控制台中cookiejar中的cookie列表以验证这一点cookie确实存在
  3. cookiejar转储所有cookie,并获得某种确认,它已经完成(如console.log('no errors'))

已经通过了硬饼干的文档,我有麻烦的步骤2和3,在这2只是显示一个空数组和3抛出TypeError: undefined is not a function

我的代码如下:

//npm install request
var request = require('request');
//special request that puts cookies in cookiejar
var cookieRequest = request.defaults( { jar : cookiejar } )
//npm install tough-cookie
var tough = require('tough-cookie');
//request the Store API
var store = tough.Store
var Cookie = tough.Cookie;
var cookiejar = new tough.CookieJar();
//load up google.com, I assume google would set some cookies in cookiejar
cookieRequest("http://google.com",function(error, response, body){
    if (!error && response.statusCode==200){
        console.log("requestDone")
    }
});
//request to see the cookies in cookiejar - at the moment it's returning an empty array, 
//would have expected something like ['cookie' : data ]
cookiejar.getCookies("http://google.com",function(err,cookies){
    console.log(cookies)
});
//here I want to dump whatever cookies were stored in cookiejar - at the moment this is 
//throwing a 'TypeError: undefined is not a function' and can't figure out why
cookiejar.store.removeCookies("http://google.com",function(err){
    console.log(err)
});
还有npm-request的文档

我知道这个问题是两年前的问题了,但我一直在试图找出这个问题的答案。我想我知道解决办法了。试试这个:

cookiejar._jar.store.removeCookies(...)