微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 postman 中的 pre-runScript 提取 cookie/令牌并将其设置为变量?

如何解决如何使用 postman 中的 pre-runScript 提取 cookie/令牌并将其设置为变量?

我正在尝试在邮递员(集合级别)中运行一个预运行脚本,该脚本执行一个简单的获取请求,以获取某个令牌,通过该令牌我将能够将其发送到下一个端点的正文请求中。

我已经设法做到了,但实际上,我得到的令牌来自上次运行,而不是当前运行导致我在发出第二个端点的 post 请求时获得状态代码 400

here below is a simple pre-run script run on collection level

Here I'm setting in tests a method to extract the needed token and set it as global var

here is the token that I have extracted in the pre-run and using it in the body req

down below u will see that the submitted token in the body request is from the previous run and not matching the current highlighted one

解决方法

您应该了解预请求和测试脚本之间的区别:

预先请求:

顾名思义就是在发送请求之前执行

测试脚本

发送请求后执行

还要明白什么是pm.sendRequest()

这是从脚本会话执行一些请求

所以在你的代码中你所做的是:

  1. 执行实际邮递员请求
  2. 存储检索到的 cookie
  3. 期望它是您在 pm.sendRequest 中获得的 cookie

这是错误的,您在测试中提取的 cookie 来自实际邮递员请求而不是 pm.sendRequest

您可以改为在您的预请求中使用

pm.sendRequest("https://reqres.in/user",function(req,res){
    pm.globals.set("xsrf",res.cookie)
    
})

这个 cookie 和 pm.cookies 来自两个不同的请求

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。