Improvement request: Pre-request Variable assignment is NULL while environment variable assignment is OK

Hi, I’ve got quite an interesting case

         pm.sendRequest({
        url: 'AUTHURL',
        method: 'POST',
        header: {
            'Content-type': 'application/json',
            'Accept':  '*/*'
        },
        body: {
            mode: 'raw',
            raw: JSON.stringify({
                login: env_variables.client_id,
                password:env_variables.client_secret
                })   
        }
    }, (err, res) => {
        if (err) {
            console.error('Error while generating a bearer token:', err);
        } else {
            console.log(res.text()); // i can see data here
            var {access_token} =  res.text();  //  
            console.log(access_token); // outputs null
            env_variables.auth_token = res.text(); //OK. I can see token in my environment.
            pm.environment.set('auth_token', res.text()); //OK. I can see token in my collection
            pm.environment.set("OAuth_Timestamp", new Date());
            // Set the ExpiresInTime variable to the time given in the response if it exists
            //pm.environment.set("ExpiresInTime", expiresInTime);
            }
    });

The response is text/plain. See inline comments. It is interesting that an assignment of the text variable results in that variable being null , as if assignment hasn’t been performed. When assigning the response of the request directly to the environment variable it works.

P.S this is a simple variable, so serialization/deserialization shouldn’t matter here, but i did try to play around with JSON conversions just for fun. It didn’t change much the result.

Thanks for your attention

EDIT: i modified my post with the latest info.

What happens when you remove the {} from around the local variable name?

var access_token =  res.text()  // we don't add semi-column

I’m not a JS expert but I don’t believe you can deconstruct plain text, so I’m guessing that’s why that returns null.

removing {} from the local variable name works. Are we expected to use different variable notations depending whether the JSON or plain text is assigned to it?

If you’re adding brackets to a local variable, you’re doing that for a particular reason - Like deconstructing an object or an array.

Those are not needed if you’re not doing that and are just saving a value to a variable.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.