从预请求脚本中保存变量以在新请求中使用

Save Variable from a Pre-request script to use in a new Request

我想 运行 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])

但是,我想简化事情并将 UUID 生成器请求插入预请求部分,这样我就不需要两个单独的请求来完成这项工作。但是当插入与上述先前请求相同的信息以设置这些变量时,它不起作用。

我目前的Pre-request脚本报错(下):

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