0

I'd like to use requestjs to make requests and share the cookies between multiple javascript files and even multiple servers. For that reason I'm storing the cookies in a database as a string and retrieve them when needed.

The string looks like this which should be compliant to tough-cookie

[{"domain":"domain.com","path":"/","secure":true,"expires":"2018-06-19T15:36:04.000Z","key":"key1","value":"val1","httpOnly":false,"hostOnly":true},{"domain":"domain.com","path":"/","secure":true,"expires":"2018-06-19T15:36:04.000Z","key":"key2","value":"val2","httpOnly":false,"hostOnly":true}]

How can I get requestjs to use those cookies? The tough-cookie object has a method fromJSON(string) which I suppose is what I need.

So supposedly I think I should be able to do

var cookies = '[{"domain":"domain.com","path":"/","secure":true,"expires":"2018-06-19T15:36:04.000Z","key":"key1","value":"val1","httpOnly":false,"hostOnly":true},{"domain":"domain.com","path":"/","secure":true,"expires":"2018-06-19T15:36:04.000Z","key":"key2","value":"val2","httpOnly":false,"hostOnly":true}]';

var j = request.jar();
j.fromJSON(cookies);

request.get({ url: 'https:/url.com', jar : j}, 
function(error, response, body) {
         console.log(body);
});

but this gives the error TypeError: j.fromJSON is not a function

How can I get request to use the cookies string fetched from the database?

maddo7
  • 4,503
  • 6
  • 31
  • 51

1 Answers1

0

It works to directly access the object to input the cookies but I don't know if this is the best solution:

TOUGH = require('tough-cookie');

var cookies = '[{"domain":"domain.com","path":"/","secure":true,"expires":"2018-06-19T15:36:04.000Z","key":"key1","value":"val1","httpOnly":false,"hostOnly":true},{"domain":"domain.com","path":"/","secure":true,"expires":"2018-06-19T15:36:04.000Z","key":"key2","value":"val2","httpOnly":false,"hostOnly":true}]';

var j = request.jar();
cookies = JSON.parse(cookies);
for(i = 0; i < cookies.length; i++) {
    var cookie = new TOUGH.Cookie(cookies[i]);
       var domain = cookie.canonicalizedDomain();

       if (!j._jar.store.idx[domain]) {
        j._jar.store.idx[domain] = {};
    }
    if (!j._jar.store.idx[domain][cookie.path]) {
        j._jar.store.idx[domain][cookie.path] = {};
    }

j._jar.store.idx[domain][cookie.path][cookie.key] = cookie;
}

//this will use the set cookies

request.get({ url: 'https:/url.com', jar : j}, 
function(error, response, body) {
         console.log(body);
});
maddo7
  • 4,503
  • 6
  • 31
  • 51