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

2.8k Views Asked by At

I want to do a very simple task:

  1. make an http request (npm install request) to http://google.com and save its cookie to cookiejar
  2. see a list of cookies in cookiejar in the console to verify that the cookie is indeed there
  3. dump all cookies from cookiejar and get some sort of confirmation that it's done (like console.log('no errors'))

Having gone through the docs for tough-cookie, I'm having trouble with steps 2 and 3, in that 2 just shows an empty array and 3 throws out TypeError: undefined is not a function

My code below:

//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)
});

Also FYI the docs for npm-request

1

There are 1 best solutions below

1
On

I know this question is 2 years old, but I've been trying to figure out the answer to this question as well. I think i know the solution. Try this instead:

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