0

我想使用 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 字符串的请求?

4

1 回答 1

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);
});
于 2017-06-22T14:22:45.683 回答