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

I’d like to run a Pre-request script in POSTMAN that sends a request to a UUID generator API and saves the UUIDs as variables. Which I can call in the body of the request since they are required there.

Originally, I have two separate requests (1) a request to the UUID Generator API (2) and another to my private API. I’m able to set the 3 UUIDs as variables and call them to the body following request to my private API no problem and it works. Like so:

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}}",

Side note: The only way I figured out how to get individualized raw text data from a response is by using .split and the line the data is one, pm.response.text().split(" ")[1])

HOWEVER, I’d like to simplify things and insert the UUID Generator Request in the Pre-Request section so I don’t need two separate Requests to make this work. But when inserting the same information that works in the prior request above to set these variables, it doesn’t work.

The Pre-request script I have so far gives an error (below):

    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

Basically whichever different variations I try in collectionVariables.set in the Pre-request script….

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

I receive errors that otherwise I wouldn’t get if it was it’s own Request (which works)

This leads me to believe it may be the inner workings of the Pre-Request Script I have.

Answer

You were nearly there. Array starts with [0] and you need to declare the response as res, as placed in the function:

pm.sendRequest({
    url: "https://www.uuidgenerator.net/api/version1/3",
    method: 'GET'
    }, function(err, res){
pm.collectionVariables.set("UUID_1", res.text().split("rn")[0])
pm.collectionVariables.set("UUID_2", res.text().split("rn")[1])
pm.collectionVariables.set("UUID_3", res.text().split("rn")[2])
});
console.log(pm.response);