【问题标题】:How to store and reuse cookies in Postman?Postman中如何存储和重复使用cookies?
【发布时间】:2015-01-29 08:05:52
【问题描述】:

我正在使用Postman 来测试和使用 API。

对于登录 url,API 需要发送带有 username 和 password 作为字段的 POST 请求。我这样做了,我收到了一个 200 响应,其中包含我已登录的消息。

然后我尝试另一个请求来获取用户数据。但是,我收到了我未登录的回复。

我意识到这个问题很可能是因为我登录时发送给我的 cookie 没有包含在下一个 Postman 请求中。

所以我的问题是,如何保存和包含 cookie 以供将来的请求使用?

【问题讨论】:

  • @CodyBugstien,你解决了这个问题吗,我也遇到了同样的问题

标签: cookies httprequest session-cookies postman


【解决方案1】:

将要使用的cookie值存储在全局变量中。在登录请求的Tests选项卡中,写入

postman.setGlobalVariable('key', postman.getResponseCookie("cookieName").value);

将Headers 选项卡中的值作为cookie 传递给获取用户请求:

Cookie | cookieName={{key}}

【讨论】:

  • 我相信这可能是过时的代码?它现在似乎产生了一个空引用错误。
【解决方案2】:

我尝试使用 Ashutosh 的答案,但出现错误。我猜这是因为 Postman 的脚本 API 发生了变化?

无论如何,以下对我有用:

  1. 在将返回您要保存的 cookie 的请求的 Tests 选项卡中,写入
pm.globals.set('<your key>', pm.cookies.get('<cookie name>'));
  1. 然后,如 Ashutosh 的回答中所述,通过将键设置为 cookie 并将相应的值设置为 &lt;your cookie name&gt;={{&lt;global variable name&gt;}};,将 cookie 添加到标头。

我在Postman sandbox API reference 找到了这方面的文档。

【讨论】:

    【解决方案3】:

    (2020 年 12 月 18 日更新,使用没有拦截器的原生 Postman 应用) 读取 cookie 的传统方式对我不起作用pm.cookies.get('&lt;cookie name&gt;') .这是一个自动将身份验证 cookie 附加到集合中的所有请求的解决方法:

    // The test scripts below run after the api /login returns the response
    
    const authCookie = pm.response.headers.idx(3).value
    /* 
    pm.response.headers.idx(3) is equal to:
    {key: "Set-Cookie", value: "xs=eyJhb; Max-Age=3600; Path=/; Expires=Fri, 18 Dec 2020 04:40:34 GMT; HttpOnly; Secure; SameSite=None"} 
    */
    
    const token = authCookie.substring(3, authCookie.indexOf(';'))
    pm.collectionVariables.set('xs_value', token);
    

    然后将这个预请求脚本添加到整个集合中:

    // Scripts below runs before any request within a collection is sent
    
    const token = pm.collectionVariables.get('xs_value')
    pm.request.headers.upsert({ key: 'Cookie', value: `xs=${token}` })
    

    享受吧!

    更多关于如何attach headers to requests的信息

    【讨论】:

      【解决方案4】:

      谷歌浏览器中似乎有两个拦截器插件。确保安装correct one。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-17
        • 2021-08-20
        • 2019-07-29
        • 2018-08-09
        • 2022-11-30
        • 2016-11-17
        • 2021-04-09
        • 2014-03-31
        相关资源
        最近更新 更多