【问题标题】:Set Cookies via String通过字符串设置 Cookie
【发布时间】:2017-06-22 22:22:45
【问题描述】:

我想使用 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

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

【问题讨论】:

    标签: javascript node.js cookies request requestjs


    【解决方案1】:

    可以直接访问对象输入cookies,但不知道是不是最好的解决方案:

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

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 1970-01-01
      • 2015-10-12
      • 2011-08-25
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      相关资源
      最近更新 更多