通过字符串设置Cookies

时间:2017-06-20 15:49:15

标签: javascript node.js cookies request requestjs

我想使用requestjs发出请求并在多个javascript文件甚至多个服务器之间共享cookie。 出于这个原因,我将cookie作为字符串存储在数据库中,并在需要时检索它们。

字符串看起来应该符合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}]

如何让requestjs使用这些cookie? tough-cookie对象有一个fromJSON(string)方法,我想这就是我需要的方法。

据说我认为我应该可以做到

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

但这会产生错误TypeError: j.fromJSON is not a function

如何获取使用从数据库中提取的cookie字符串的请求?

1 个答案:

答案 0 :(得分:0)

它可以直接访问对象以输入cookie,但我不知道这是否是最佳解决方案:

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