【问题标题】:How can you use cookies with superagent?如何将 cookie 与 superagent 一起使用?
【发布时间】:2012-08-08 19:44:27
【问题描述】:

我正在使用 express 进行 cookie 会话管理,如下所示:

req.session.authentication = auth;

我使用类似

的方式验证经过身份验证的网址
if(!req.session.authentication){res.send(401);}

现在我正在使用 mocha、superagentshould 为 URL 构建测试,但是我似乎找不到使用 superagent 获取/设置 cookie 的方法。我什至尝试在经过身份验证的测试之前请求登录,但它不起作用,

我已经尝试在 mocha BDD 套件的 before 语句中将请求添加到登录中,但是它仍然告诉我该请求是未经授权的,我已经测试了来自浏览器的请求的身份验证,但它不是在套件中工作有什么想法吗?

【问题讨论】:

    标签: node.js mocha.js superagent


    【解决方案1】:

    2020 +

    一个干净的方法是:

    • 创建一个简单的 cookie 存储
    • 抽象设置 Cookie 以在每个请求中发送它
    • 仅在需要时更新 cookie

    请注意,我使用的是 graphql,所以我保留了相同的 URL,但您可以将其设为参数:

    const graph = agent =>
      agent.post('/graph')
        .set('cookie', cookieStore.get());
    
    const handleCookie = res =>
      cookieStore.set(res.headers['set-cookie'][0]);
    
    let currentCookie="";
    const cookieStore = {
      set: cookie=>{currentCookie=cookie},
      get: cookie=>currentCookie,
    };
    
    module.exports = {graph,connectTestUser,handleCookieResponse};
    

    您现在可以只使用 graph(agent) 发送请求并在您有可能更新 cookie(设置或清除)的响应时使用 handleCookie(response) ,例如:

    graph(agent).end((err,res) => {
      if (err) return done(err);
      res.statusCode.should.equal(200);
      handleCookie(res);
      return done();
    });
    

    【讨论】:

    • 不应该是res.header['set-cookie']而不是res.headers['set-cookie']吗?
    【解决方案2】:

    使用superagent.agent()(而不是普通的旧superagent)使请求具有持久性cookie。请参阅'Preserving cookies' in the superagent docs,或代码示例:agency.jscontroller.test.js

    【讨论】:

    • 请注意,superagent.agent() 对大多数请求定义都有 serious, undocumented issues in how it handles cookies - 任何比 get(url,opts,cb) 更复杂的东西都需要挂钩到未记录的私有方法。
    • 事实上文档也没有提到cookies。我真的开始喜欢这个库,并且因为作者而寄予厚望,但如果你想使用会话 cookie,它就没有用了。
    • 这不起作用/如果它确实还不够...有人可以提供一个如何工作的例子......
    【解决方案3】:

    似乎下面的代码可以正常工作;

    req.set('Cookie', "cookieName1=cookieValue1;cookieName2=cookieValue2");

    【讨论】:

    • 这对我使用 Django {"Cookie": "csrftoken=token here"} 无效
    【解决方案4】:

    如果问题在于为 CORS 请求发送 cookie,请使用 .withCredentials() 方法 described here

    request
      .get('http://localhost:4001/')
      .withCredentials()
      .end(function(err, res) { })
    

    【讨论】:

      【解决方案5】:

      既然你提到你需要得到设置cookie:

      获取:

      const request = await Superagent.get('...')
      
      const cookie = request.header['set-cookie']
      

      设置:

      Superagent.post('...').set('Cookie', 'cookie_info')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-01
        • 2011-09-03
        • 2018-02-01
        • 2016-02-14
        • 1970-01-01
        • 2016-05-28
        • 2016-11-14
        相关资源
        最近更新 更多