javascript - 保存预请求脚本中的变量以在新请求中使用
问题描述
我想在 POSTMAN 中运行一个预请求脚本,它将请求发送到 UUID 生成器 API 并将 UUID 保存为变量。我可以在请求正文中调用它,因为那里需要它们。
最初,我有两个单独的请求 (1) 一个对 UUID 生成器 API 的请求 (2) 另一个对我的私有 API 的请求。我可以将 3 个 UUID 设置为变量,并根据对我的私有 API 的请求将它们调用到正文中,这没问题,并且可以正常工作。像这样:
GET https://www.uuidgenerator.net/api/version1/3
pm.collectionVariables.set("UUID_1", pm.response.text().split(" ")[1])
pm.collectionVariables.set("UUID_2", pm.response.text().split(" ")[2])
pm.collectionVariables.set("UUID_3", pm.response.text().split(" ")[3])
**Response:**
1. f3600940-3684-11ec-8d3d-0242ac130003
2. f3600b70-3684-11ec-8d3d-0242ac130003
3. f3600c6a-3684-11ec-8d3d-0242ac130003
**Variables in body of next Request:**
"data": {
"uuid": "{{UUID_1}}",
"uuid2": "{{UUID_2}}",
"uuid3": "{{UUID_3}}",
旁注:我想出如何从响应中获取个性化原始文本数据的唯一方法是使用.split
数据行,pm.response.text().split(" ")[1])
但是,我想简化一些事情并在 Pre-Request 部分插入 UUID 生成器请求,因此我不需要两个单独的请求来完成这项工作。但是,当插入与上述先前请求相同的信息来设置这些变量时,它不起作用。
到目前为止,我的预请求脚本给出了一个错误(如下):
pm.sendRequest({
url: "https://www.uuidgenerator.net/api/version1/3",
method: 'GET'
}, function (err, res) {
pm.collectionVariables.set("UUID_1", pm.response.text().split(" ")[1])
pm.collectionVariables.set("UUID_2", pm.response.text().split(" ")[2])
pm.collectionVariables.set("UUID_3", pm.response.text().split(" ")[3])
});
POSTMAN Error:
There was an error in evaluating the Pre-request Script:Error: Cannot read property 'text' of undefined
collectionVariables.set
基本上我在预请求脚本中尝试的任何不同变体......
pm.collectionVariables.set("UUID_1", pm.response.text().split(" ")[1])
OR
pm.collectionVariables.set("UUID_2", pm.response.split(" ")[2])
OR
pm.collectionVariables.set("UUID_3", pm.response.[3])
我收到错误,否则如果它是自己的请求我不会得到(有效)
这让我相信这可能是我拥有的预请求脚本的内部工作原理。
解决方案
你快到了。数组以 [0] 开头,您需要将响应声明为 res,如放置在函数中:
pm.sendRequest({
url: "https://www.uuidgenerator.net/api/version1/3",
method: 'GET'
}, function(err, res){
pm.collectionVariables.set("UUID_1", res.text().split("\r\n")[0])
pm.collectionVariables.set("UUID_2", res.text().split("\r\n")[1])
pm.collectionVariables.set("UUID_3", res.text().split("\r\n")[2])
});
console.log(pm.response);
推荐阅读
- python-3.6 - 用于打印函数包含的所有变量的 Python Dunder 方法?用于自定义调试装饰器
- node.js - Express 和 EJS - 不编译。我该如何解决?
- python - 我可以在没有显卡的情况下使用张量流 GPU 吗?将培训外包给 AWS/Cloud?
- java - 为什么我的测试没有触发我的过滤器?
- rest - 方法 PUT IN Powershell,问题:400 Malformed Error Converting,
- python - 函数不使用更新的变量?
- scala - 如何将泛型用于 Scala (2.12) 宏?
- c# - asp.net Swashbuckle 集成导致“无法加载文件或程序集'System.Web.Http,版本 = 4.0.0.0”
- python - Python:*args 和远程函数中的列表之间的区别
- c# - ASP.Net Identity 的 IdentityDbContext 是否调用 DbContext?