首页 > 解决方案 > 保存预请求脚本中的变量以在新请求中使用

问题描述

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

我收到错误,否则如果它是自己的请求我不会得到(有效)

这让我相信这可能是我拥有的预请求脚本的内部工作原理。

标签: javascriptjavaapirequestpostman

解决方案


你快到了。数组以 [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);

推荐阅读